dlt645_0x33333433.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package protocol
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "github.com/gogf/gf/os/glog"
  6. "strconv"
  7. )
  8. type Dlt_0x33333433 struct {
  9. //接收表号
  10. DeviceAddress []byte
  11. //表号
  12. DeviceID string
  13. //正向有功总电能
  14. WH float64
  15. }
  16. func (e *Dlt_0x33333433) MsgID() MsgID {
  17. return Msgdlt_0x33333433
  18. }
  19. func (e *Dlt_0x33333433) Encode(ctx *PacketContext) ([]byte, error) {
  20. writer := NewWriter()
  21. // 接收符号
  22. writer.Write([]byte{0x68})
  23. writer.Write(ctx.GetReceiveAddress())
  24. writer.Write([]byte{0x68, 0x11, 0x04, 0x33, 0x33, 0x34, 0x33})
  25. //cs效验位
  26. var one byte
  27. for _, v := range writer.Bytes() {
  28. one += v
  29. }
  30. writer.WriteByte(one)
  31. // 功能码
  32. writer.WriteByte(0x16)
  33. return writer.Bytes(), nil
  34. }
  35. func (e *Dlt_0x33333433) Decode(ctx *PacketContext, dataByte []byte) (data Data, err error) {
  36. bytea := dataByte[1:7]
  37. for i, j := 0, len(bytea)-1; i < j; i, j = i+1, j-1 {
  38. bytea[i], bytea[j] = bytea[j], bytea[i]
  39. }
  40. e.DeviceID = hex.EncodeToString(bytea)
  41. //正向总电能每个字节-33,1-4,分别为,小数位,个位,百位,万位
  42. byteb := make([]byte, 4)
  43. for i := 0; i < 4; i++ {
  44. byteb[i] = dataByte[14+i] - 0x33
  45. }
  46. e.WH, err = stringToWP(hex.EncodeToString(byteb))
  47. if err != nil {
  48. return data, err
  49. }
  50. glog.Debugf("数据读取成功:表号:%s,正向有功总电能:%2f kWh", e.DeviceID, e.WH)
  51. data.ActivePower = e.WH
  52. data.DataType = IsPower
  53. return data, err
  54. }
  55. func stringToWP(s string) (float64, error) {
  56. a0, _ := strconv.ParseFloat(s[0:2], 64)
  57. a1, _ := strconv.ParseFloat(s[2:4], 64)
  58. a2, _ := strconv.ParseFloat(s[4:6], 64)
  59. a3, _ := strconv.ParseFloat(s[6:8], 64)
  60. res, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", a0/100+a1+a2*100+a3*10000), 64)
  61. return res, nil
  62. }