dlt645_0x33333935.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package protocol
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "github.com/gogf/gf/os/glog"
  6. "strconv"
  7. )
  8. type Dlt_0x33333935 struct {
  9. //接收表号
  10. DeviceAddress []byte
  11. //表号
  12. DeviceID string
  13. //当前总功率因数
  14. PowerFactor float64
  15. }
  16. func (e *Dlt_0x33333935) MsgID() MsgID {
  17. return Msgdlt_0x33333935
  18. }
  19. func (e *Dlt_0x33333935) 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, 0x39, 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_0x33333935) 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, 2)
  43. for i := 0; i < 2; i++ {
  44. byteb[i] = dataByte[14+i] - 0x33
  45. }
  46. e.PowerFactor, err = stringToPowerFactor(hex.EncodeToString(byteb))
  47. if err != nil {
  48. return data, err
  49. }
  50. glog.Debugf("数据读取成功:表号:%s,当前总功率因数:%2f", e.DeviceID, e.PowerFactor)
  51. return data, nil
  52. }
  53. func stringToPowerFactor(s string) (float64, error) {
  54. a0, _ := strconv.ParseFloat(s[0:2], 64)
  55. a1, _ := strconv.ParseFloat(s[2:4], 64)
  56. res, _ := strconv.ParseFloat(fmt.Sprintf("%.4f", a0/10000+a1/10), 64)
  57. return res, nil
  58. }