fwh_mqtt_envelope.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package fwh_mqtt
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "hash/crc32"
  6. "time"
  7. )
  8. const (
  9. topicPrefixS2C = "fwh/s2c/"
  10. topicPrefixC2S = "fwh/c2s/"
  11. defaultSnno = 123 // 设备不按 snno 应答,固定值即可
  12. equipTypeGateway = 0 // 外层设备类型:网关 IBG
  13. )
  14. // FwhMqttMsg FWH MQTT 报文外层
  15. type FwhMqttMsg struct {
  16. CmdType uint `json:"cmdType"` // 业务类型标识
  17. Crc string `json:"crc"` // dataArea 数据字符串的CRC
  18. DataArea interface{} `json:"dataArea"` // 数据域
  19. EquipNo string `json:"equipNo"` // 设备编号 SN
  20. Len int `json:"len"` // dataArea 数据长度
  21. Snno uint `json:"snno"` // 序号
  22. TimeStamp int64 `json:"timeStamp"` // 时间戳
  23. Type uint `json:"type"` // 设备类型 0:设备网关IBG
  24. }
  25. // NewEnvelope 构造外层:len 为 dataArea 序列化字节长度,crc 为其 CRC32 IEEE 大写十六进制
  26. func NewEnvelope(cmdType uint, equipNo string, dataArea any) (FwhMqttMsg, error) {
  27. b, err := json.Marshal(dataArea)
  28. if err != nil {
  29. return FwhMqttMsg{}, err
  30. }
  31. return FwhMqttMsg{
  32. CmdType: cmdType,
  33. Type: equipTypeGateway,
  34. Snno: defaultSnno,
  35. TimeStamp: time.Now().Unix(),
  36. EquipNo: equipNo,
  37. DataArea: dataArea,
  38. Len: len(b),
  39. Crc: fmt.Sprintf("%08X", crc32.ChecksumIEEE(b)),
  40. }, nil
  41. }
  42. // S2CTopic 服务端 → 设备方向的 topic,如 S2CTopic("mng/" + sn)
  43. func S2CTopic(name string) string { return topicPrefixS2C + name }
  44. // C2STopic 设备 → 服务端方向的 topic
  45. func C2STopic(name string) string { return topicPrefixC2S + name }