TB 如何计算每一次上报使用了多少流量
正文与代码来自原稿。评估蜂窝流量套餐时,不能只算 JSON 本体。
1、要点
MQTT 上行总流量大致包括:
- MQTT 固定头 / 可变头
- Topic 名称长度
- Payload
- TCP/IP(及可选 TLS)开销
2、近似公式
text
总流量 (bytes) ≈ 固定头 + 可变头 + Payload + 网络头
total_bytes ≈ 50 + len(topic) + payload_bytes(50 为网络头经验值;MQTT 固定头可再按约 5 字节计。)
3、JS 估算示例
js
function getByteLength(str) {
var byteLength = 0;
for (var i = 0; i < str.length; i++) {
var charCode = str.charCodeAt(i);
if (charCode <= 0x7f) byteLength += 1;
else if (charCode <= 0x7ff) byteLength += 2;
else if (charCode <= 0xffff) byteLength += 3;
else byteLength += 4;
}
return byteLength;
}
var topic = "v1/devices/me/telemetry";
var payload = JSON.stringify({
deviceId: "ABC123",
temperature: 26.5,
humidity: 55.3,
status: "OK"
});
var topicBytes = getByteLength(topic);
var payloadBytes = getByteLength(payload);
var mqttHeader = 5;
var networkHeader = 50;
var totalBytes = topicBytes + payloadBytes + mqttHeader + networkHeader;
var totalBits = totalBytes * 8;
console.log("Topic:", topicBytes, "B");
console.log("Payload:", payloadBytes, "B");
console.log("Total:", totalBytes, "B (≈", (totalBits / 1024).toFixed(2), "Kb)");
// 示例约 Topic 17B + Payload 68B → Total ~140B4、更精确时还要加
- CONNECT / SUBSCRIBE / PING(通常很小)
- KeepAlive、TCP 握手
- TLS 握手(重连可达数 KB 级)
建议:
text
实际月流量 ≈ 理论值 × 1.1 ~ 1.25、小结
按「单次字节 × 上报频率 × 设备数 × 安全系数」估套餐;缩短 Topic、压缩 JSON 键名可明显降流量。
