dlt645_0x33333835.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package protocol
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "github.com/gogf/gf/os/glog"
  6. "strconv"
  7. )
  8. type Dlt_0x33333835 struct {
  9. //接收表号
  10. DeviceAddress []byte
  11. //表号
  12. DeviceID string
  13. //当前视在功率
  14. ApparentPower float64
  15. }
  16. func (e *Dlt_0x33333835) MsgID() MsgID {
  17. return Msgdlt_0x33333835
  18. }
  19. func (e *Dlt_0x33333835) Encode(ctx *PacketContext) ([]byte, error) {
  20. writer := NewWriter()
  21. // 接收符号
  22. writer.Write([]byte{0x68})
  23. writer.Write(e.DeviceAddress)
  24. writer.Write([]byte{0x68, 0x11, 0x04, 0x33, 0x33, 0x38, 0x35})
  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_0x33333835) 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, 3)
  43. for i := 0; i < 3; i++ {
  44. byteb[i] = dataByte[14+i] - 0x33
  45. }
  46. e.ApparentPower, err = stringToApparentPower(hex.EncodeToString(byteb))
  47. if err != nil {
  48. return data, err
  49. }
  50. glog.Debugf("数据读取成功:表号:%s,当前视在功率:%2f", e.DeviceID, e.ApparentPower)
  51. return data, nil
  52. }
  53. func stringToApparentPower(s string) (float64, error) {
  54. a0, _ := strconv.ParseFloat(s[0:2], 64)
  55. a1, _ := strconv.ParseFloat(s[2:4], 64)
  56. a2, _ := strconv.ParseFloat(s[4:6], 64)
  57. res, _ := strconv.ParseFloat(fmt.Sprintf("%.4f", a0/10000+a1/100+a2), 64)
  58. return res, nil
  59. }