#github.com/xulang-org/packages/mqtt
Xu 0.16.0 API
import: mqtt #github.com/xulang-org/packages/mqtt
counts: 12 functions, 18 methods, 4 types, 0 constants, 0 method sets
MQTT 3.1.1 lightweight messaging and IoT driver for Xu. Features Pure binary Wire Protocol implementation in 100% pure Xu. Full CONNECT / CONNACK session handshake. PUBLISH support for QoS 0 and QoS 1 with PUBACK confirmation. SUBSCRIBE with SUBACK confirmation. PINGREQ / PINGRESP heartbeat maintenance. Graceful DISCONNECT.
github.com/xulang-org/packages · 1.17.2 · Install and use
Examples · API declarations
Examples
These sources come from the official examples repository and can be copied or downloaded. Run them with a local Xu SDK in the complete project; network, database, and desktop examples require the corresponding services or assets.
25_standalone_mqtt/main.xu
Required SDK: Xu 0.8.3 · Complete project · Download source
@main
mqtt #github.com/xulang-org/packages/mqtt
#os
fn main() int {
println("=== MQTT 3.1.1 IoT & Messaging Standalone Integration Test ===")
addr := "127.0.0.1:1883"
client_id := "xu_test_node_42"
println("Connecting to MQTT Broker at " + addr + " (client_id=" + client_id + ")...")
$client := mqtt.open(addr + "", client_id + "") >>> (err) {
println("MQTT connect failed: " + err.msg())
<< 1
}
println("1. MQTT Session established successfully (CONNACK code=0).")
// 2. Ping heartbeat
is_alive := client.ping()
println("2. PINGREQ/PINGRESP heartbeat: " + str(is_alive))
// 3. Subscribe
topic := "devices/status"
client.subscribe(topic + "", 0) >>> (err) {
println("Subscribe failed: " + err.msg())
<< 1
}
println("3. Subscribed to topic: " + topic + " (QoS 0)")
// 4. Publish QoS 0
payload_0 := "{\"status\": \"online\", \"battery\": 98}"
client.publish(topic + "", payload_0 + "", 0) >>> (err) {
println("Publish QoS 0 failed: " + err.msg())
<< 1
}
println("4. Published QoS 0 message: " + payload_0)
// 5. Publish QoS 1 (waits for PUBACK)
payload_1 := "{\"critical_alert\": \"temperature threshold exceeded\"}"
client.publish(topic + "", payload_1 + "", 1) >>> (err) {
println("Publish QoS 1 failed: " + err.msg())
<< 1
}
println("5. Published QoS 1 message (received PUBACK confirmation).")
// 6. Disconnect
client.disconnect()
println("6. Gracefully disconnected from Broker.")
// 7. MQTT Connection Pool Deep Verification
println("7. Testing MQTT Connection Pool with Reuse & Concurrency...")
pool := mqtt.open_pool(addr + "", "xu_mqtt_pool", 5)
$c1 := pool.get() >>> (err) {
println("Pool get c1 failed: " + err.msg())
<< 1
}
fd_first := c1.fd
c1_ok := c1.ping()
println(" Pool c1 ping: " + str(c1_ok) + " (fd=" + str(fd_first) + ")")
pool.put(c1)
// Verify Pool Connection REUSE
$c2 := pool.get() >>> (err) {
println("Pool get c2 failed: " + err.msg())
<< 1
}
fd_second := c2.fd
if fd_first == fd_second {
println(" [PASS] MQTT Pool Connection REUSE verified! (fd1 == fd2: " + str(fd_first) + ")")
} else {
println(" [WARN] fd1 != fd2 (fd1=" + str(fd_first) + ", fd2=" + str(fd_second) + ")")
}
// Concurrent borrow another connection
$c3 := pool.get() >>> (err) {
println("Pool get c3 failed: " + err.msg())
<< 1
}
fd_third := c3.fd
if fd_second != fd_third {
println(" [PASS] MQTT Pool Multi-connection concurrency verified! (fd2=" + str(fd_second) + " != fd3=" + str(fd_third) + ")")
}
// Pool Direct Publish
pool.publish("sensors/pool_alert", "temperature=29C", 0) >>> (err) {
<< 1
}
println(" [PASS] MQTT Pool direct publish succeeded.")
pool.put(c2)
pool.put(c3)
pool.close()
println(" [PASS] MQTT Pool closed cleanly.")
println("=== MQTT Tests Completed Successfully! ===")
<< 0
}
API declarations
open
pub fn open(addr string, client_id string) Client
Purpose
Open resource or establish connection. Throws on failure; handle the error or propagate it to the caller.
Parameters
addr string- address (string)
client_id string- client_id (string)
Returns
Client — a value of this type
See usage example
open_pool
pub fn open_pool(addr string, id_prefix string, max_idle int) Pool
Purpose
Open pool.
Parameters
addr string- address (string)
id_prefix string- id_prefix (string)
max_idle int- max_idle (int)
Returns
Pool — a value of this type
See usage example
struct Client
pub struct Client {
pub fd int
pub addr string
pub client_id string
pub next_pid int
}
Purpose
Mqtt Client session maintaining connection and operations.
Public fields
fd int- file descriptor
addr string- address
client_id string- field (string)
next_pid int- field (int)
struct Message
pub struct Message {
pub topic string
pub payload string
pub qos int
}
Purpose
Structure encapsulating topic, payload, qos.
Public fields
topic string- field (string)
payload string- field (string)
qos int- field (int)
connect_opts
pub fn connect_opts(addr string, client_id string, username string, password string, clean_session bool, keepalive int) Client
Purpose
Connect opts. Throws on failure; handle the error or propagate it to the caller.
Parameters
addr string- address (string)
client_id string- client_id (string)
username string- username (string)
password string- password (string)
clean_session bool- clean_session (bool)
keepalive int- keepalive (int)
Returns
Client — a value of this type
connect
pub fn connect(addr string, client_id string) Client
Purpose
Execute connect. Throws on failure; handle the error or propagate it to the caller.
Parameters
addr string- address (string)
client_id string- client_id (string)
Returns
Client — a value of this type
connect_auth
pub fn connect_auth(addr string, client_id string, username string, password string) Client
Purpose
Connect auth. Throws on failure; handle the error or propagate it to the caller.
Parameters
addr string- address (string)
client_id string- client_id (string)
username string- username (string)
password string- password (string)
Returns
Client — a value of this type
($&Client) ping
pub fn (c $&Client) ping() bool
Purpose
Send a ping heartbeat request to verify connection liveness.
Parameters
c $&Client- The
Client instance used by this call (exclusive borrow).
Returns
bool — true or false
($&Client) publish
pub fn (c $&Client) publish(topic string, payload string, qos int) int
Purpose
Publish message data to the given topic or channel. Throws on failure; handle the error or propagate it to the caller.
Parameters
c $&Client- The
Client instance used by this call (exclusive borrow).
topic string- topic (string)
payload string- payload (string)
qos int- qos (int)
Returns
int — a value of this type
($&Client) subscribe
pub fn (c $&Client) subscribe(topic string, qos int) int
Purpose
Execute subscribe on $&Client. Throws on failure; handle the error or propagate it to the caller.
Parameters
c $&Client- The
Client instance used by this call (exclusive borrow).
topic string- topic (string)
qos int- qos (int)
Returns
int — a value of this type
($&Client) read_message
pub fn (c $&Client) read_message() Message
Purpose
Operation on $&Client: read message. Throws on failure; handle the error or propagate it to the caller.
Parameters
c $&Client- The
Client instance used by this call (exclusive borrow).
Returns
Message — a value of this type
($&Client) disconnect
pub fn (c $&Client) disconnect() int
Purpose
Execute disconnect on $&Client.
Parameters
c $&Client- The
Client instance used by this call (exclusive borrow).
Returns
int — a value of this type
($&Client) close
pub fn (c $&Client) close() int
Purpose
Operation on $&Client: close the resource.
Parameters
c $&Client- The
Client instance used by this call (exclusive borrow).
Returns
int — a value of this type
struct Pool
pub struct Pool {
pub addr string
pub id_prefix string
pub idle chan int
pub max_idle int
pub seq chan int
}
Purpose
Connection Pool for MQTT 3.1.1 clients. Uses channel of socket file descriptors for lightweight and high-throughput pooling.
Public fields
addr string- address
id_prefix string- field (string)
idle chan int- field (channel; type chan int)
max_idle int- field (int)
seq chan int- field (channel; type chan int)
new_pool
pub fn new_pool(addr string, id_prefix string, max_idle int) Pool
Purpose
Construct pool.
Parameters
addr string- address (string)
id_prefix string- id_prefix (string)
max_idle int- max_idle (int)
Returns
Pool — a value of this type
(&Pool) get
pub fn (p &Pool) get() Client
Purpose
Execute get on &Pool. Throws on failure; handle the error or propagate it to the caller.
Parameters
p &Pool- The
Pool instance used by this call (borrow).
Returns
Client — a value of this type
(&Pool) put_conn
pub fn (p &Pool) put_conn(fd int)
Purpose
Operation on &Pool: put connection.
Parameters
p &Pool- The
Pool instance used by this call (borrow).
fd int- file descriptor (int)
Returns
This call does not return a value.
(&Pool) put
pub fn (p &Pool) put(c Client)
Purpose
Store or update the value associated with the specified key.
Parameters
p &Pool- The
Pool instance used by this call (borrow).
c Client- byte or character code (Client)
Returns
This call does not return a value.
(&Pool) publish
pub fn (p &Pool) publish(topic string, payload string, qos int) int
Purpose
Publish message data to the given topic or channel. Throws on failure; handle the error or propagate it to the caller.
Parameters
p &Pool- The
Pool instance used by this call (borrow).
topic string- topic (string)
payload string- payload (string)
qos int- qos (int)
Returns
int — a value of this type
(&Pool) close
Purpose
Operation on &Pool: close the resource.
Parameters
p &Pool- The
Pool instance used by this call (borrow).
Returns
This call does not return a value.
encode_u16
pub fn encode_u16(n int) string
Purpose
Encode u16 data.
Parameters
n int- count, length, or limit (int)
Returns
string — result string
decode_u16
pub fn decode_u16(s &string, off int) int
Purpose
Decode u16 data.
Parameters
s &string- source string (read-only borrow; caller keeps the original; type &string)
off int- offset (int)
Returns
int — a value of this type
encode_str
pub fn encode_str(text string) string
Purpose
Encode str data.
Parameters
text string- text (string)
Returns
string — result string
encode_var_len
pub fn encode_var_len(val int) string
Purpose
Encode var len data.
Parameters
val int- value (int)
Returns
string — result string
struct TlsClient
pub struct TlsClient {
pub conn transport.Conn
pub host string
pub port int
}
Purpose
Mqtt Client session maintaining connection and operations.
Public fields
conn transport.Conn- field (transport.Conn)
host string- host
port int- port
tls_connect
pub fn tls_connect(endpoint string, default_port int) TlsClient
Purpose
Tls connect. Throws on failure; handle the error or propagate it to the caller.
Parameters
endpoint string- endpoint (string)
default_port int- default_port (int)
Returns
TlsClient — a value of this type
tls_connect_config
pub fn tls_connect_config(endpoint string, default_port int, cfg tls.Config) TlsClient
Purpose
Tls connect config. Throws on failure; handle the error or propagate it to the caller.
Parameters
endpoint string- endpoint (string)
default_port int- default_port (int)
cfg tls.Config- cfg (tls.Config)
Returns
TlsClient — a value of this type
($&TlsClient) write_all
pub fn (c $&TlsClient) write_all(data string) int
Purpose
Operation on $&TlsClient: write all. Throws on failure; handle the error or propagate it to the caller.
Parameters
c $&TlsClient- The
TlsClient instance used by this call (exclusive borrow).
data string- data (string)
Returns
int — a value of this type
($&TlsClient) read
pub fn (c $&TlsClient) read(max int) string
Purpose
Operation on $&TlsClient: read up to max bytes. Throws on failure; handle the error or propagate it to the caller.
Parameters
c $&TlsClient- The
TlsClient instance used by this call (exclusive borrow).
max int- maximum (int)
Returns
string — result string
($&TlsClient) read_exact
pub fn (c $&TlsClient) read_exact(need int) string
Purpose
Operation on $&TlsClient: read exact. Throws on failure; handle the error or propagate it to the caller.
Parameters
c $&TlsClient- The
TlsClient instance used by this call (exclusive borrow).
need int- need (int)
Returns
string — result string
($&TlsClient) close
pub fn (c $&TlsClient) close() int
Purpose
Operation on $&TlsClient: close the resource. Throws on failure; handle the error or propagate it to the caller.
Parameters
c $&TlsClient- The
TlsClient instance used by this call (exclusive borrow).
Returns
int — a value of this type
($&TlsClient) set_deadline
pub fn (c $&TlsClient) set_deadline(t_ns int) int
Purpose
Operation on $&TlsClient: set deadline. Throws on failure; handle the error or propagate it to the caller.
Parameters
c $&TlsClient- The
TlsClient instance used by this call (exclusive borrow).
t_ns int- t_ns (int)
Returns
int — a value of this type
($&TlsClient) set_read_deadline
pub fn (c $&TlsClient) set_read_deadline(t_ns int) int
Purpose
Operation on $&TlsClient: set read deadline. Throws on failure; handle the error or propagate it to the caller.
Parameters
c $&TlsClient- The
TlsClient instance used by this call (exclusive borrow).
t_ns int- t_ns (int)
Returns
int — a value of this type
($&TlsClient) set_write_deadline
pub fn (c $&TlsClient) set_write_deadline(t_ns int) int
Purpose
Operation on $&TlsClient: set write deadline. Throws on failure; handle the error or propagate it to the caller.
Parameters
c $&TlsClient- The
TlsClient instance used by this call (exclusive borrow).
t_ns int- t_ns (int)
Returns
int — a value of this type