package protocol import ( "encoding/hex" "fmt" "github.com/gogf/gf/os/glog" "strconv" ) type Dlt_0x33333735 struct { //接收表号 DeviceAddress []byte //表号 DeviceID string //当前总无功功率 ReactivePower float64 } func (entity *Dlt_0x33333735) MsgID() MsgID { return Msgdlt_0x33333735 } func (entity *Dlt_0x33333735) Encode(ctx *PacketContext) ([]byte, error) { writer := NewWriter() // 接收符号 writer.Write([]byte{0x68}) writer.Write(entity.DeviceAddress) writer.Write([]byte{0x68, 0x11, 0x04, 0x33, 0x33, 0x37, 0x35}) //cs效验位 var one byte for _, v := range writer.Bytes() { one += v } writer.WriteByte(one) // 功能码 writer.WriteByte(0x16) return writer.Bytes(), nil } func (entity *Dlt_0x33333735) Decode(ctx *PacketContext, data []byte) (result string, err error) { bytea := data[1:7] for i, j := 0, len(bytea)-1; i < j; i, j = i+1, j-1 { bytea[i], bytea[j] = bytea[j], bytea[i] } entity.DeviceID = hex.EncodeToString(bytea) //正向总电能每个字节-33,1-4,分别为,小数位,个位,百位,万位 byteb := make([]byte, 3) for i := 0; i < 3; i++ { byteb[i] = data[14+i] - 0x33 } entity.ReactivePower, err = stringToReactivePower(hex.EncodeToString(byteb)) if err != nil { return result, err } glog.Debugf("数据读取成功:表号:%s,当前总无功功率:%2f", entity.DeviceID, entity.ReactivePower) result = fmt.Sprintf("%s:%2f", "当前总无功功率", entity.ReactivePower) return result, nil } func stringToReactivePower(s string) (float64, error) { a0, _ := strconv.ParseFloat(s[0:2], 64) a1, _ := strconv.ParseFloat(s[2:4], 64) a2, _ := strconv.ParseFloat(s[4:6], 64) res := a0*0.0001 + a1*0.01 + a2 return res, nil }