This page is also available in the other languages: English Deutsch

MQTT

MQTT is a lightweight, publish-subscribe, machine to machine network protocol for message queue/message queuing service.

The “mqtt” package can be used to send and receive MQTT messages. The package is available since hkknx v2.7.0 and supports MQTT v3.1.1.

Send Message

A Publisher is used to send messages. As the name suggests, a publisher can send (“publish”) messages. An MQTT message contains the payload data (bytes) and the topic. The Publish method is available for sending a message.

 1var mqtt = import("mqtt")
 2
 3// Create new configuration and the address
 4// specify the broker.
 5var config = new(mqtt.Config)
 6config.Addr = "broker.emqx.io:1883"
 7// Username and password are at
 8// not required for this broker
 9// config.Username = "..."
10// config.Password = "..."
11
12var publisher, err = mqtt.NewPublisher(config)
13if err != nil {
14     println(err)
15     return
16}
17
18var msg = make(mqtt.Message)
19msg.Bytes = "Hello"
20msg.Topic = "hello/world"
21err = publisher.Publish(msg)
22return err

This example establishes a connection to the broker broker.emqx.io on port 1883 and sends the message “Hello” to the topic “hello/world”.

The Publish method sends the message to the broker with Quality of Service (QoS) 0. Additional methods are available for higher service qualities. You can read more about this on the documentation page.

Receive messages

A Subscriber is used to receive messages. A subscriber can subscribe to messages from one or more topics. The broker then forwards messages to the subscriber.

In the following example, a connection is reestablished to the broker broker.emqx.io on port 1883. The topic hello/world is then subscribed and waited in the for loop until a message is received.

 1var mqtt = import("mqtt")
 2
 3// Create new configuration and the address
 4// specify the broker.
 5var config = new(mqtt.Config)
 6config.Addr = "broker.emqx.io:1883"
 7// Username and password are at
 8// not required for this broker
 9// config.Username = "..."
10// config.Password = "..."
11
12subscriber, err = mqtt.NewSubscriber(config)
13if err != nil {
14     println(err)
15     return
16}
17
18err = subscriber.Subscribe("hello/world")
19if err != nil {
20     println(err)
21return
22}
23
24for {
25msg = <-subscriber.C()
26if msg == nil { // nil means that the connection is down
27return subscriber.Err() // stop execution
28}
29
30printf("%s %s\n", msg.Topic, msg.Bytes)
31}

© Matthias Hochgatterer – MastodonGithubRésumé