关于MQTT固定标头结构? [英] Regarding the MQTT fixed header structure?
问题描述
我正在尝试实现MQTT
库.并且根据一个教程,MQTT
消息的固定标头应该看起来像发布的图片中所示.
i am trying to implement a MQTT
library. And according to a tutorial, the fixed header of the MQTT
message should look like as shown in the posted picture.
也在同一教程中,我发现固定标头的编码方法写为:
Also in the same tutorial, i found that the encodeing method of the fixed header is written as:
mqtt.write((byte) ((retain ? 1 : 0) | qos << 1 | (dup ? 1 : 0) << 3 | type << 4));
我的问题是,根据发布的固定标头规范,字段retain
,qos
,dup
和msg type
应该具有1
,2
,1
和4
位.
My Question is, according to the fixed header specifications posted, the fields retain
, qos
, dup
and the msg type
should have 1
, 2
, 1
and 4
bits respectively.
为什么将msg type
字段扩展到5位<< 4",而将字段dup
扩展到4 bits
<< 3"?
why the msg type
field is expanded upto 5 bits "<<4" and the field dup
is expanded upto 4 bits
"<<3" ?
Fixed_Header
推荐答案
为什么将msg类型字段扩展到5位"<<< 4",并且将字段dup扩展到4位<<< 3"?
why the msg type field is expanded upto 5 bits "<<4" and the field dup is expanded upto 4 bits "<<3" ?
<<
不会扩展"该字段,它会移动它离开.
<<
doesn't "expand" the field, it shifts it left.
最初,我们的每个数字如下所示:
Initially, each of our numbers looks like this:
bit: | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
======================================================================
|------------- type ------------|
|- dup -|
|----- qos -----|
| retain|
假设每个数字都在该字段的有效范围内,则它们已经是正确的宽度.具体来说,type
的值可以为0到15,因此(最多)4位宽; dup
和retain
必须为0或1,因此只有1位宽; qos
的值可以是0到3,即2位宽.
Assuming that each of the numbers is in a valid range for that field, then they are already the correct width. Specifically, type
can have a value from 0 to 15, so it is (up to) 4 bits wide; dup
and retain
must be 0 or 1 so are only 1 bit wide; qos
can have a value from 0 to 3, which is 2 bits wide.
但是,它们在错误的位置.它们卡在低位(3,2,1,0)中.我们需要将它们向左移动以将它们放置到正确的位置:
But, they are in the wrong place. They are stuck down in the low bits (3,2,1,0). We need to shift them left to get them to the correct positions:
bit: | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
======================================================================
|----------- type<<4 -----------|
| dup<<3|
|---- qos<<1 ---|
| retain|
例如,dup
被左移3位,因为我们要在其下3个空格(实际上是值为0的位). retain
不需要移动,因为它恰好位于正确的位置.
For example, dup
is shifted left 3 bits because we want 3 spaces (actually bits of value 0) below it. retain
does not need to be shifted because it happened to be in the correct place already.
一旦所有位都放置在正确的位置,它们就使用 ORed 一起 c20>给出该字节:
Once all the bits are in the correct place, they are ORed together using |
to give this byte:
bit: | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
======================================================================
|----------- type<<4 -----------| dup<<3|---- qos<<1 ---| retain|
想要的是什么.
这篇关于关于MQTT固定标头结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!