低空智控平台 后端go
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

54 lines
1.4 KiB

package mqtt
import (
"encoding/json"
"time"
)
// Envelope MQTT 消息通用外层(协议文档 §4)
//
// {
// "requestId": "req-uuid" | null,
// "dockId": "dock-...",
// "droneSn": "..." | null,
// "timestamp": 1784700000000,
// "payload": { ... }
// }
type Envelope struct {
RequestID string `json:"requestId"`
EventID string `json:"eventId"`
Version int64 `json:"version"`
DockID string `json:"dockId"`
DroneSN string `json:"droneSn"`
Timestamp int64 `json:"timestamp"`
Payload json.RawMessage `json:"payload"`
}
// ParseEnvelope 解析通用外层;payload 缺失(无外层的历史扁平消息)时把整个消息体当作 payload。
func ParseEnvelope(data []byte) *Envelope {
var env Envelope
if err := json.Unmarshal(data, &env); err != nil {
return &Envelope{Payload: data}
}
if len(env.Payload) == 0 {
env.Payload = data
}
return &env
}
// NewEnvelope 构造下行外层;payload 为业务字段(内部自动 marshal),timestamp 取当前毫秒。
func NewEnvelope(requestID, dockID, droneSN string, payload any) *Envelope {
var raw json.RawMessage
if payload != nil {
if b, err := json.Marshal(payload); err == nil {
raw = b
}
}
return &Envelope{
RequestID: requestID,
DockID: dockID,
DroneSN: droneSN,
Timestamp: time.Now().UnixMilli(),
Payload: raw,
}
}