dlt645_0x33333533.go 1.7 KB

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