package lampControl import ( "encoding/hex" "fmt" "github.com/valyala/bytebufferpool" "strconv" ) func (o DataPack) GetLampTurnOnOffCommand() *bytebufferpool.ByteBuffer { //初始化成员 o.Start = 0x68 o.Addr = o.Addr o.Start2 = 0x68 o.Ctl = 0x1E o.Data = append([]byte{0x00, 0x00, 0x60, 0x07, 0x01}, o.Data...) //按路开关灯 o.DataLen = uint8(len(o.Data)) o.End = 0x16 //addr tmpAddr := EncodeAddr(o.Addr) if tmpAddr == nil { return nil } //序列化 buf := bytebufferpool.Get() buf.WriteByte(o.Start) buf.Write(tmpAddr) buf.WriteByte(o.Start2) buf.WriteByte(o.Ctl) buf.WriteByte(o.DataLen) if o.DataLen > 0 { TmpData := make([]byte, o.DataLen) for i, b := range o.Data { TmpData[i] = b + 0x33 } buf.Write(TmpData) } //计算校验码 o.Cs = CheckSum(buf.Bytes()) buf.WriteByte(o.Cs) buf.WriteByte(o.End) return buf } func (o DataPack) GetLampSetBrightCommand(brightness int) *bytebufferpool.ByteBuffer { //初始化成员 o.Start = 0x68 o.Addr = o.Addr o.Start2 = 0x68 o.Ctl = 0x1E hexValue := fmt.Sprintf("%02x", brightness) decodeString, _ := hex.DecodeString(hexValue) o.Data = append([]byte{0x00, 0x00, 0x60, 0x09, 0x01}, decodeString...) //按路调光照度 o.DataLen = uint8(len(o.Data)) o.End = 0x16 //addr tmpAddr := EncodeAddr(o.Addr) if tmpAddr == nil { return nil } //序列化 buf := bytebufferpool.Get() buf.WriteByte(o.Start) buf.Write(tmpAddr) buf.WriteByte(o.Start2) buf.WriteByte(o.Ctl) buf.WriteByte(o.DataLen) if o.DataLen > 0 { TmpData := make([]byte, o.DataLen) for i, b := range o.Data { TmpData[i] = b + 0x33 } buf.Write(TmpData) } //计算校验码 o.Cs = CheckSum(buf.Bytes()) buf.WriteByte(o.Cs) buf.WriteByte(o.End) return buf } func CheckSum(data []byte) uint8 { var sum uint64 for _, c := range data { sum += uint64(c) } return uint8(sum % 256) } func EncodeAddr(Addr string) []byte { var bytes []byte for i := 0; i < len(Addr); i += 2 { // 直接解析并添加到字节数组中 if b, err := strconv.ParseUint(Addr[i:i+2], 16, 8); err == nil { bytes = append(bytes, byte(b)) } } // 反转字节顺序 for i, j := 0, len(bytes)-1; i < j; i, j = i+1, j-1 { bytes[i], bytes[j] = bytes[j], bytes[i] } return bytes }