バイナリデータの作り方です
バイナリデータ扱うには以下のパッケージを利用するとよいかもです
実際に, MQTT V3.1 Protocol Specification から "2. Message format" 内の "2.1. Fixed header" 部分を扱ってみます
(名称は適当)
import struct
from enum import Enum
class MessageType(Enum):
Reserved = 0 # Reserved
CONNECT = 1 # Client request to connect to Server
CONNACK = 2 # Connect Acknowledgment
PUBLISH = 3 # Publish message
PUBACK = 4 # Publish Acknowledgment
PUBREC = 5 # Publish Received (assured delivery part 1)
PUBREL = 6 # Publish Release (assured delivery part 2)
PUBCOMP = 7 # Publish Complete (assured delivery part 3)
SUBSCRIBE = 8 # Client Subscribe request
SUBACK = 9 # Subscribe Acknowledgment
UNSUBSCRIBE = 10 # Client Unsubscribe request
UNSUBACK = 11 # Unsubscribe Acknowledgment
PINGREQ = 12 # PING Request
PINGRESP = 13 # PING Response
DISCONNECT = 14 # Client is Disconnecting
# Reserved = 15 # Reserved
flagsDUP = 0b1000
flagsQoS1 = 1 <<1
flagsQoS2 = 2 <<1
flagsQoS3 = 3 <<1
flagsRETAIN = 1
struct
でネットワーク・バイトオーダーを(複数バイトにまたがる数値が存在するようなら)指定し バイト列へ
(バイト列を作成できたら送信など)
>>> b1 = MessageType.PUBACK.value <<4 | flagsDUP | flagsQoS2
>>> b2 = 100
>>>
>>> bs = struct.pack('!2B', b1, b2)
>>> bs.hex()
'4c64'
>>> struct.unpack('!BB', bs)
(76, 100)