1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- package protocol
- import (
- "encoding/hex"
- "fmt"
- "github.com/gogf/gf/os/glog"
- "strconv"
- )
- type Dlt_0x33333433 struct {
- //接收表号
- DeviceAddress []byte
- //表号
- DeviceID string
- //正向有功总电能
- WH float64
- }
- func (e *Dlt_0x33333433) MsgID() MsgID {
- return Msgdlt_0x33333433
- }
- func (e *Dlt_0x33333433) Encode(ctx *PacketContext) ([]byte, error) {
- writer := NewWriter()
- // 接收符号
- writer.Write([]byte{0x68})
- writer.Write(ctx.GetReceiveAddress())
- writer.Write([]byte{0x68, 0x11, 0x04, 0x33, 0x33, 0x34, 0x33})
- //cs效验位
- var one byte
- for _, v := range writer.Bytes() {
- one += v
- }
- writer.WriteByte(one)
- // 功能码
- writer.WriteByte(0x16)
- return writer.Bytes(), nil
- }
- func (e *Dlt_0x33333433) Decode(ctx *PacketContext, dataByte []byte) (data Data, err error) {
- bytea := dataByte[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]
- }
- e.DeviceID = hex.EncodeToString(bytea)
- //正向总电能每个字节-33,1-4,分别为,小数位,个位,百位,万位
- byteb := make([]byte, 4)
- for i := 0; i < 4; i++ {
- byteb[i] = dataByte[14+i] - 0x33
- }
- e.WH, err = stringToWP(hex.EncodeToString(byteb))
- if err != nil {
- return data, err
- }
- glog.Debugf("数据读取成功:表号:%s,正向有功总电能:%2f kWh", e.DeviceID, e.WH)
- data.ActivePower = e.WH
- data.DataType = IsPower
- return data, err
- }
- func stringToWP(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)
- a3, _ := strconv.ParseFloat(s[6:8], 64)
- res, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", a0/100+a1+a2*100+a3*10000), 64)
- return res, nil
- }
|