dlt645_0x33333433.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. WP float64
  15. }
  16. func (entity *Dlt_0x33333433) MsgID() MsgID {
  17. return Msgdlt_0x33333433
  18. }
  19. func (entity *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 (entity *Dlt_0x33333433) Decode(ctx *PacketContext, data []byte) (result string, err error) {
  36. bytea := data[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. entity.DeviceID = hex.EncodeToString(bytea)
  41. //正向总电能每个字节-33,1-4,分别为,小数位,个位,百位,万位
  42. byteb := make([]byte, 4)
  43. for i := 0; i < 4; i++ {
  44. byteb[i] = data[14+i] - 0x33
  45. }
  46. entity.WP, err = stringToWP(hex.EncodeToString(byteb))
  47. if err != nil {
  48. return "", err
  49. }
  50. glog.Debugf("数据读取成功:表号:%s,正向有功总电能:%2f kWh", entity.DeviceID, entity.WP)
  51. result = fmt.Sprintf("%s:%2f kWh", "正向有功总电能", entity.WP)
  52. return entity.DeviceID, nil
  53. }
  54. func stringToWP(s string) (float64, error) {
  55. a0, _ := strconv.ParseFloat(s[0:2], 64)
  56. a1, _ := strconv.ParseFloat(s[2:4], 64)
  57. a2, _ := strconv.ParseFloat(s[4:6], 64)
  58. a3, _ := strconv.ParseFloat(s[6:8], 64)
  59. res := a0*0.01 + a1 + a2*100 + a3*10000
  60. return res, nil
  61. }