MQTT

Aus TippvomTibb
Zur Navigation springen Zur Suche springen

Message Queue/Queuing Telemetry Transport

Es ist mal wieder soweit. Heute habe ich meine Arbeit an meinem 'MQTT-System' wieder aufgenommen. Schnell mal die aktuelle Installationssituation gecheckt und den Rahmen für die anstehenden Tests abgesteckt.

Dieser Artikel dient mir in erster Linie als Leitfaden und Dokumentation der Konfiguartionsmöglichkeiten des mosquitto MQTT-Systems. Ob ich die Artikel der MQTT-Clients (Ardiuno, ESP8266, RasPi, ...) auch hier in den Artikel packe, habe ich noch nicht entschieden.

Installation

Als MQTT-Paket wird mosquitto bei openSuSE mitgeliefert. Ich habe mich bewußt erst mal gegen die integrierte Variante in FHEM (MQTT2_SERVER) entschieden, da ein Blick ins Wiki und ins Forum von FHEM wieder das übliche Durcheinander zeigt. Da verliert man sich zu schnell in irgendwelchen Spezialproblemen. Also mal nachschauen, ob ich das Paket auf dem Server schon installiert hatte.

zypper se MQTT

Es ist zum Mäusemelken. Mosquitto wird so nicht gefunden, also besser immer gleich mit der Option -d (Search also in package summaries and descriptions. Default: false) suchen.

zypper se -d MQTT
Loading repository data...
Reading installed packages...

S | Name               | Summary                                          | Type
--+--------------------+--------------------------------------------------+-----------
  | libmosquitto1      | Shared C Library for mosquitto                   | package
  | libmosquittopp1    | Shared C++ Library for mosquitto                 | package
  | libpaho-mqtt-devel | Development files for MQTT C Client library      | package
  | libpaho-mqtt1      | Library implementing the MQTT client             | package
  | mosquitto          | A MQTT v3.1/v3.1.1 Broker                        | package
  | mosquitto          | A MQTT v3.1/v3.1.1 Broker                        | srcpackage
  | mosquitto-clients  | Client for Mosquitto                             | package
  | mosquitto-devel    | Development files for mosquitto                  | package
  | openSUSE-2020-726  | Recommended update for paho-mqtt-c               | patch
  | paho-mqtt-c        | MQTT C Client                                    | srcpackage
  | python2-paho-mqtt  | MQTT version 3.11 client class                   | package
  | python3-paho-mqtt  | MQTT version 3.11 client class                   | package
  | rabbitmq-server    | A message broker supporting AMQP, STOMP and MQTT | package

und mit

zypper in mosquitto

installieren.

Die Clients (mosquitto_pub mosquitto_rr mosquitto_sub) am besten gleich mit installieren.

Broker auf dem Server starten

systemctl status mosquitto
● mosquitto.service - Mosquitto MQTT v3.1/v3.1.1 Broker
   Loaded: loaded (/usr/lib/systemd/system/mosquitto.service; disabled; vendor preset: disabled)
   Active: inactive (dead)
     Docs: man:mosquitto.conf(5)
           man:mosquitto(8)

Das ist schon mal gut, dass im Paket eine passende .service-Datei mitgeliefert wurde, ansonsten hätte ich jetzt wieder mein Template anpassen müssen. Glück gehabt.

systemctl enable mosquitto
Created symlink /etc/systemd/system/multi-user.target.wants/mosquitto.service → /usr/lib/systemd/system/mosquitto.service.

Jetzt kann man den Broker starten. Den Blick in Configdateien spare ich mir mal solange alles so funktioniert wie ich es erwarte.

systemctl start mosquitto

Und mit status gleich mal nachschauen was der Server (Broker) so macht.

systemctl status mosquitto


● mosquitto.service - Mosquitto MQTT v3.1/v3.1.1 Broker
   Loaded: loaded (/usr/lib/systemd/system/mosquitto.service; enabled; vendor preset: disabled)
   Active: active (running) since Fri 2021-01-15 18:54:04 CET; 7s ago
     Docs: man:mosquitto.conf(5)
           man:mosquitto(8)
 Main PID: 13312 (mosquitto)
    Tasks: 1
   CGroup: /system.slice/mosquitto.service
           └─13312 /usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf

Jan 15 18:54:04 server systemd[1]: Started Mosquitto MQTT v3.1/v3.1.1 Broker.
Jan 15 18:54:04 server mosquitto[13312]: 1610733244: mosquitto version 1.5.7 starting
Jan 15 18:54:04 server mosquitto[13312]: 1610733244: Config loaded from /etc/mosquitto/mosquitto.conf.
Jan 15 18:54:04 server mosquitto[13312]: 1610733244: Opening ipv4 listen socket on port 1883.
Jan 15 18:54:04 server mosquitto[13312]: 1610733244: Opening ipv6 listen socket on port 1883.

Aha. Der Server läuft, Config liegt unter /etc/mosquitto und er ist auf Port 1883 über IPv4 und IPv6 erreichbar.

Auf meinem anderen Server lief's nicht so gut. Da bekam ich eine Fehlermeldung.

● mosquitto.service - Mosquitto MQTT v3.1/v3.1.1 Broker
   Loaded: loaded (/usr/lib/systemd/system/mosquitto.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Fri 2021-01-15 17:21:51 CET; 1h 37min ago
     Docs: man:mosquitto.conf(5)
           man:mosquitto(8)
  Process: 12886 ExecStart=/usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf (code=exited, status=1/FAILURE)
 Main PID: 12886 (code=exited, status=1/FAILURE)

Jan 15 17:21:51 fhem.clx.local systemd[1]: Started Mosquitto MQTT v3.1/v3.1.1 Broker.
Jan 15 17:21:51 fhem.clx.local mosquitto[12886]: 1610727711: Loading config file /etc/mosquitto/conf.d/default.conf
Jan 15 17:21:51 fhem.clx.local mosquitto[12886]: 1610727711: Loading config file /etc/mosquitto/conf.d/websockets.conf
Jan 15 17:21:51 fhem.clx.local mosquitto[12886]: 1610727711: mosquitto version 1.6.9 starting
Jan 15 17:21:51 fhem.clx.local mosquitto[12886]: 1610727711: Config loaded from /etc/mosquitto/mosquitto.conf.
Jan 15 17:21:51 fhem.clx.local mosquitto[12886]: 1610727711: Opening ipv4 listen socket on port 1883.
Jan 15 17:21:51 fhem.clx.local mosquitto[12886]: 1610727711: Error: Address already in use
Jan 15 17:21:51 fhem.clx.local systemd[1]: mosquitto.service: Main process exited, code=exited, status=1/FAILURE
Jan 15 17:21:51 fhem.clx.local systemd[1]: mosquitto.service: Unit entered failed state.
Jan 15 17:21:51 fhem.clx.local systemd[1]: mosquitto.service: Failed with result 'exit-code'.

Hier liegt eine Kollision auf dem Port 1883 vor. Mal schauen wer oder was da blockiert.

ss -nltpa |grep 1883
LISTEN   0        32                  0.0.0.0:1883              0.0.0.0:*        users:(("perl",pid=26203,fd=13))

Perl PID 26203 ist der Überltäter und das ist FHEM. Das ist dann das Überbleibsel meiner letzten Versuchsreihe.

grep MQTT /etc/fhem/fhem*
/etc/fhem/fhem.conf:define MQTT MQTT2_SERVER 1883 global

Ok. Da kann ich dann später bei der FHEM-Integration weiter machen.

First Contact

Mal eine Nachricht vom Client (worker) an den Server (broker) senden.

mosquitto_pub -h server -p 1883 -t /haus/test -m "hallo welt"

Auf dem Client kommt schon mal keine Fehlermeldung. Gut.

Mal schauen, ob auf dem Server was passiert.

server:~ # tcpdump -i eth2 src 192.168.178.11 and port 1883
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth2, link-type EN10MB (Ethernet), capture size 262144 bytes
19:14:41.201621 IP 192.168.178.11.48330 > 192.168.178.10.mqtt: Flags [S], seq 1113973064, win 64240, options [mss 1460,sackOK,TS val 298691237 ecr 0,nop,wscale 7], length 0
19:14:41.201980 IP 192.168.178.11.48330 > 192.168.178.10.mqtt: Flags [.], ack 3184443970, win 502, options [nop,nop,TS val 298691238 ecr 605516974], length 0
19:14:41.202232 IP 192.168.178.11.48330 > 192.168.178.10.mqtt: Flags [P.], seq 0:37, ack 1, win 502, options [nop,nop,TS val 298691238 ecr 605516974], length 37
19:14:41.202466 IP 192.168.178.11.48330 > 192.168.178.10.mqtt: Flags [.], ack 5, win 502, options [nop,nop,TS val 298691238 ecr 605516975], length 0
19:14:41.202588 IP 192.168.178.11.48330 > 192.168.178.10.mqtt: Flags [P.], seq 37:61, ack 5, win 502, options [nop,nop,TS val 298691238 ecr 605516975], length 24
19:14:41.202609 IP 192.168.178.11.48330 > 192.168.178.10.mqtt: Flags [FP.], seq 61:63, ack 5, win 502, options [nop,nop,TS val 298691238 ecr 605516975], length 2
19:14:41.202834 IP 192.168.178.11.48330 > 192.168.178.10.mqtt: Flags [.], ack 6, win 502, options [nop,nop,TS val 298691239 ecr 605516975], length 0

Das sieht doch gut aus. Das Portmapping ersetzt 1883 sogar durch '.mqtt'

Intermezzo

Gleich mal, weil so schön ist, ein wenig die Kommunikation beleuchtet. (-d schalten den Debug-Modus an)

worker:~ # mosquitto_pub -h server -p 1883 -t /haus/test -m "hallo welt" -d
Client mosq-zXegtgLVTedJw16YN0 sending CONNECT
Client mosq-zXegtgLVTedJw16YN0 received CONNACK (0)
Client mosq-zXegtgLVTedJw16YN0 sending PUBLISH (d0, q0, r0, m1, '/haus/test', ... (10 bytes))
Client mosq-zXegtgLVTedJw16YN0 sending DISCONNECT

Das ergibt auf dem Server folgende Reaktion.

Nachtrag: Ich sehe gerade 'damals' habe ich den MQTT-Pfad mit einem Slash '/' vor 'haus' eingeleitet. Das ist zwar syntaktisch erlaubt, wird aber nicht empfohlen. Super erörtert von Tinkerman [1] aber auch hier wird der Umstand gut umrissen. [2]

server:~ # tcpdump -tttt -n -A  -i eth2 src 192.168.178.11 and port 1883  
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth2, link-type EN10MB (Ethernet), capture size 262144 bytes
2021-01-15 19:22:22.156924 IP 192.168.178.11.49086 > 192.168.178.10.1883: Flags [S], seq 2229763113, win 64240, options [mss 1460,sackOK,TS val 299152192 ecr 0,nop,wscale 7], length 0
E..<z
@.@..J.......
...[..|).........h.........
...@........
2021-01-15 19:22:22.157272 IP 192.168.178.11.49086 > 192.168.178.10.1883: Flags [.], ack 932540963, win 502, options [nop,nop,TS val 299152193 ecr 605977897], length 0
E..4z.@.@..Q.......
...[..|*7.r#...........
...A$.})
2021-01-15 19:22:22.157375 IP 192.168.178.11.49086 > 192.168.178.10.1883: Flags [P.], seq 0:37, ack 1, win 502, options [nop,nop,TS val 299152193 ecr 605977897], length 37
E..Yz.@.@..+.......
...[..|*7.r#....
......
...A$.}).#..MQTT...<..mosq-zXegtgLVTedJw16YN0
2021-01-15 19:22:22.157712 IP 192.168.178.11.49086 > 192.168.178.10.1883: Flags [.], ack 5, win 502, options [nop,nop,TS val 299152193 ecr 605977898], length 0
E..4z.@.@..O.......
...[..|O7.r'...........
...A$.}*
2021-01-15 19:22:22.157824 IP 192.168.178.11.49086 > 192.168.178.10.1883: Flags [P.], seq 37:61, ack 5, win 502, options [nop,nop,TS val 299152193 ecr 605977898], length 24
E..Lz.@.@..6.......
...[..|O7.r'....s......
...A$.}*0..
/haus/testhallo welt
2021-01-15 19:22:22.157887 IP 192.168.178.11.49086 > 192.168.178.10.1883: Flags [FP.], seq 61:63, ack 5, win 502, options [nop,nop,TS val 299152193 ecr 605977898], length 2
E..6z.@.@..K.......
...[..|g7.r'...........
...A$.}*..
2021-01-15 19:22:22.158255 IP 192.168.178.11.49086 > 192.168.178.10.1883: Flags [.], ack 6, win 502, options [nop,nop,TS val 299152194 ecr 605977898], length 0
E..4..@.@.U].......
...[..|j7.r(...........
...B$.}*

Server/Broker Reaktion

Dass die Nachrichten zum Publizieren beim Server ankommen, hat man im vorangegangenen Anschnitt gesehen. Jetzt geht es darum die ordnungsgemäße Verarbeitung durch den Borker nachzuvollziehen.

1. Idee: Ich lasse den Broker auf der Konsole seinen Aktivitäten ausgegeben.

2. Idee: Ich lasse den Broker seine Aktivitäten in einem File mitloggen.

3. Idee: Ich nutzte einen Client um Debug-Informationen vom Broker abzurufen.


Stdout mit Debug-Ausgabe

server:~ # mosquitto -h
 1 mosquitto version 1.5.7
 2 
 3 mosquitto is an MQTT v3.1.1 broker.
 4 
 5 Usage: mosquitto [-c config_file] [-d] [-h] [-p port]
 6 
 7  -c : specify the broker config file.
 8  -d : put the broker into the background after starting.
 9  -h : display this help.
10  -p : start the broker listening on the specified port.
11       Not recommended in conjunction with the -c option.
12  -v : verbose mode - enable all logging types. This overrides
13       any logging options given in the config file.
14 
15 See http://mosquitto.org/ for more information.

Allerdings entfaltet die Option -v nur ohne die Option -d ihre Wirkung. Also mosquitto-Service stoppen und in der Konsole starten.

 server:~ # mosquitto -v -c /etc/mosquitto/mosquitto.conf 
1610778217: mosquitto version 1.5.7 starting
1610778217: Config loaded from /etc/mosquitto/mosquitto.conf.
1610778217: Opening ipv4 listen socket on port 1883.
1610778217: Opening ipv6 listen socket on port 1883.
1610778233: New connection from 192.168.178.11 on port 1883.
1610778233: New client connected from 192.168.178.11 as mosq-FufTGTa6x2qexVTprf (c1, k60).
1610778233: No will message specified.
1610778233: Sending CONNACK to mosq-FufTGTa6x2qexVTprf (0, 0)
1610778233: Received PUBLISH from mosq-FufTGTa6x2qexVTprf (d0, q0, r0, m0, '/haus/test', ... (10 bytes))
1610778233: Received DISCONNECT from mosq-FufTGTa6x2qexVTprf
1610778233: Client mosq-FufTGTa6x2qexVTprf disconnected.

Nach der Startmeldung kommt die Reaktion auf diesen Publish-Befehl:

mosquitto_pub -h 192.168.178.10 -p 1883 -t /haus/test -m "hallo welt" -d

Beim Client wird dieser Vorgang so kommentiert:

Client mosq-FufTGTa6x2qexVTprf sending CONNECT
Client mosq-FufTGTa6x2qexVTprf received CONNACK (0)
Client mosq-FufTGTa6x2qexVTprf sending PUBLISH (d0, q0, r0, m1, '/haus/test', ... (10 bytes))
Client mosq-FufTGTa6x2qexVTprf sending DISCONNECT

LogFile mit Debugmeldungen

Um diese Variante zu erreichen gibt es offensichtlich keine Kommandozeilen-Option. Also bleibt wohl nichts übrig als das config-File anzupassen oder ein mosquitto-debug.conf anzulegen.

Ein Blick in das Default-Config oder auch 'man mosquitto.conf' zeigt folgendes:


cat /etc/mosquitto/mosquitto.conf
# Config file for mosquitto
#
# See mosquitto.conf(5) for more information.
#
# Default values are shown, uncomment to change.
#
# Use the # character to indicate a comment, but only if it is the 
# very first character on the line.

# =================================================================
# General configuration
# =================================================================

# Time in seconds between updates of the $SYS tree.
# Set to 0 to disable the publishing of the $SYS tree.
#sys_interval 10

# Time in seconds between cleaning the internal message store of 
# unreferenced messages. Lower values will result in lower memory 
# usage but more processor time, higher values will have the 
# opposite effect.
# Setting a value of 0 means the unreferenced messages will be 
# disposed of as quickly as possible.
#store_clean_interval 10

# Write process id to a file. Default is a blank string which means 
# a pid file shouldn't be written.
# This should be set to /var/run/mosquitto.pid if mosquitto is
# being run automatically on boot with an init script and 
# start-stop-daemon or similar.
#pid_file

# When run as root, drop privileges to this user and its primary 
# group.
# Set to root to stay as root, but this is not recommended.
# If run as a non-root user, this setting has no effect.
# Note that on Windows this has no effect and so mosquitto should 
# be started by the user you wish it to run as.
#user mosquitto

# The maximum number of QoS 1 and 2 messages currently inflight per 
# client.
# This includes messages that are partway through handshakes and 
# those that are being retried. Defaults to 20. Set to 0 for no 
# maximum. Setting to 1 will guarantee in-order delivery of QoS 1 
# and 2 messages.
#max_inflight_messages 20

# QoS 1 and 2 messages will be allowed inflight per client until this limit
# is exceeded.  Defaults to 0. (No maximum)
# See also max_inflight_messages
#max_inflight_bytes 0

# The maximum number of QoS 1 and 2 messages to hold in a queue per client
# above those that are currently in-flight.  Defaults to 100. Set 
# to 0 for no maximum (not recommended).
# See also queue_qos0_messages.
# See also max_queued_bytes.
#max_queued_messages 100

# QoS 1 and 2 messages above those currently in-flight will be queued per
# client until this limit is exceeded.  Defaults to 0. (No maximum)
# See also max_queued_messages.
# If both max_queued_messages and max_queued_bytes are specified, packets will
# be queued until the first limit is reached.
#max_queued_bytes 0

# Set to true to queue messages with QoS 0 when a persistent client is
# disconnected. These messages are included in the limit imposed by
# max_queued_messages and max_queued_bytes
# Defaults to false.
# This is a non-standard option for the MQTT v3.1 spec but is allowed in
# v3.1.1.
#queue_qos0_messages false

# This option sets the maximum publish payload size that the broker will allow.
# Received messages that exceed this size will not be accepted by the broker.
# The default value is 0, which means that all valid MQTT messages are
# accepted. MQTT imposes a maximum payload size of 268435455 bytes. 
#message_size_limit 0

# This option controls whether a client is allowed to connect with a zero
# length client id or not. This option only affects clients using MQTT v3.1.1
# and later. If set to false, clients connecting with a zero length client id
# are disconnected. If set to true, clients will be allocated a client id by
# the broker. This means it is only useful for clients with clean session set
# to true.
#allow_zero_length_clientid true

# If allow_zero_length_clientid is true, this option allows you to set a prefix
# to automatically generated client ids to aid visibility in logs.
#auto_id_prefix

# This option allows persistent clients (those with clean session set to false)
# to be removed if they do not reconnect within a certain time frame.
#
# This is a non-standard option in MQTT V3.1 but allowed in MQTT v3.1.1.
#
# Badly designed clients may set clean session to false whilst using a randomly
# generated client id. This leads to persistent clients that will never
# reconnect. This option allows these clients to be removed.
#
# The expiration period should be an integer followed by one of h d w m y for
# hour, day, week, month and year respectively. For example
#
# persistent_client_expiration 2m
# persistent_client_expiration 14d
# persistent_client_expiration 1y
#
# The default if not set is to never expire persistent clients.
#persistent_client_expiration

# If a client is subscribed to multiple subscriptions that overlap, e.g. foo/#
# and foo/+/baz , then MQTT expects that when the broker receives a message on
# a topic that matches both subscriptions, such as foo/bar/baz, then the client
# should only receive the message once.
# Mosquitto keeps track of which clients a message has been sent to in order to
# meet this requirement. The allow_duplicate_messages option allows this
# behaviour to be disabled, which may be useful if you have a large number of
# clients subscribed to the same set of topics and are very concerned about
# minimising memory usage.
# It can be safely set to true if you know in advance that your clients will
# never have overlapping subscriptions, otherwise your clients must be able to
# correctly deal with duplicate messages even when then have QoS=2.
#allow_duplicate_messages false

# The MQTT specification requires that the QoS of a message delivered to a
# subscriber is never upgraded to match the QoS of the subscription. Enabling
# this option changes this behaviour. If upgrade_outgoing_qos is set true,
# messages sent to a subscriber will always match the QoS of its subscription.
# This is a non-standard option explicitly disallowed by the spec.
#upgrade_outgoing_qos false

# Disable Nagle's algorithm on client sockets. This has the effect of reducing
# latency of individual messages at the potential cost of increasing the number
# of packets being sent.
#set_tcp_nodelay false

# Use per listener security settings.
# If this option is set to true, then all authentication and access control
# options are controlled on a per listener basis. The following options are
# affected:
#
# password_file acl_file psk_file auth_plugin auth_opt_* allow_anonymous
# auto_id_prefix allow_zero_length_clientid
#
# Note that if set to true, then a durable client (i.e. with clean session set
# to false) that has disconnected will use the ACL settings defined for the
# listener that it was most recently connected to.
#
# The default behaviour is for this to be set to false, which maintains the 
# setting behaviour from previous versions of mosquitto.
#per_listener_settings false

# This option affects the scenario when a client subscribes to a topic that has
# retained messages. It is possible that the client that published the retained
# message to the topic had access at the time they published, but that access
# has been subsequently removed. If check_retain_source is set to true, the
# default, the source of a retained message will be checked for access rights
# before it is republished. When set to false, no check will be made and the
# retained message will always be published. This affects all listeners.
#check_retain_source true


# =================================================================
# Default listener
# =================================================================

# IP address/hostname to bind the default listener to. If not
# given, the default listener will not be bound to a specific 
# address and so will be accessible to all network interfaces.
# bind_address ip-address/host name
#bind_address

# Port to use for the default listener.
#port 1883

# The maximum number of client connections to allow. This is 
# a per listener setting.
# Default is -1, which means unlimited connections.
# Note that other process limits mean that unlimited connections 
# are not really possible. Typically the default maximum number of 
# connections possible is around 1024.
#max_connections -1

# Choose the protocol to use when listening.
# This can be either mqtt or websockets.
# Websockets support is currently disabled by default at compile time.
# Certificate based TLS may be used with websockets, except that
# only the cafile, certfile, keyfile and ciphers options are supported.
#protocol mqtt

# When a listener is using the websockets protocol, it is possible to serve
# http data as well. Set http_dir to a directory which contains the files you
# wish to serve. If this option is not specified, then no normal http
# connections will be possible.
#http_dir

# Set use_username_as_clientid to true to replace the clientid that a client
# connected with with its username. This allows authentication to be tied to
# the clientid, which means that it is possible to prevent one client
# disconnecting another by using the same clientid.
# If a client connects with no username it will be disconnected as not
# authorised when this option is set to true.
# Do not use in conjunction with clientid_prefixes.
# See also use_identity_as_username.
#use_username_as_clientid

# -----------------------------------------------------------------
# Certificate based SSL/TLS support
# -----------------------------------------------------------------
# The following options can be used to enable SSL/TLS support for 
# this listener. Note that the recommended port for MQTT over TLS
# is 8883, but this must be set manually.
#
# See also the mosquitto-tls man page.

# At least one of cafile or capath must be defined. They both 
# define methods of accessing the PEM encoded Certificate 
# Authority certificates that have signed your server certificate 
# and that you wish to trust.
# cafile defines the path to a file containing the CA certificates.
# capath defines a directory that will be searched for files
# containing the CA certificates. For capath to work correctly, the
# certificate files must have ".crt" as the file ending and you must run
# "openssl rehash <path to capath>" each time you add/remove a certificate.
#cafile
#capath

# Path to the PEM encoded server certificate.
#certfile

# Path to the PEM encoded keyfile.
#keyfile

# This option defines the version of the TLS protocol to use for this listener.
# The default value allows v1.2, v1.1 and v1.0. The valid values are tlsv1.2
# tlsv1.1 and tlsv1.
#tls_version

# By default a TLS enabled listener will operate in a similar fashion to a
# https enabled web server, in that the server has a certificate signed by a CA
# and the client will verify that it is a trusted certificate. The overall aim
# is encryption of the network traffic. By setting require_certificate to true,
# the client must provide a valid certificate in order for the network
# connection to proceed. This allows access to the broker to be controlled
# outside of the mechanisms provided by MQTT.
#require_certificate false

# If require_certificate is true, you may set use_identity_as_username to true
# to use the CN value from the client certificate as a username. If this is
# true, the password_file option will not be used for this listener.
# This takes priority over use_subject_as_username.
# See also use_subject_as_username.
#use_identity_as_username false

# If require_certificate is true, you may set use_subject_as_username to true
# to use the complete subject value from the client certificate as a username.
# If this is true, the password_file option will not be used for this listener.
# See also use_identity_as_username
#use_subject_as_username false

# If you have require_certificate set to true, you can create a certificate
# revocation list file to revoke access to particular client certificates. If
# you have done this, use crlfile to point to the PEM encoded revocation file.
#crlfile

# If you wish to control which encryption ciphers are used, use the ciphers
# option. The list of available ciphers can be obtained using the "openssl
# ciphers" command and should be provided in the same format as the output of
# that command.
# If unset defaults to DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:@STRENGTH
#ciphers DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:@STRENGTH

# -----------------------------------------------------------------
# Pre-shared-key based SSL/TLS support
# -----------------------------------------------------------------
# The following options can be used to enable PSK based SSL/TLS support for
# this listener. Note that the recommended port for MQTT over TLS is 8883, but
# this must be set manually.
#
# See also the mosquitto-tls man page and the "Certificate based SSL/TLS
# support" section. Only one of certificate or PSK encryption support can be
# enabled for any listener.

# The psk_hint option enables pre-shared-key support for this listener and also
# acts as an identifier for this listener. The hint is sent to clients and may
# be used locally to aid authentication. The hint is a free form string that
# doesn't have much meaning in itself, so feel free to be creative.
# If this option is provided, see psk_file to define the pre-shared keys to be
# used or create a security plugin to handle them.
#psk_hint

# Set use_identity_as_username to have the psk identity sent by the client used
# as its username. Authentication will be carried out using the PSK rather than
# the MQTT username/password and so password_file will not be used for this
# listener.
#use_identity_as_username false

# When using PSK, the encryption ciphers used will be chosen from the list of
# available PSK ciphers. If you want to control which ciphers are available,
# use the "ciphers" option.  The list of available ciphers can be obtained
# using the "openssl ciphers" command and should be provided in the same format
# as the output of that command.
#ciphers

# =================================================================
# Extra listeners
# =================================================================

# Listen on a port/ip address combination. By using this variable 
# multiple times, mosquitto can listen on more than one port. If 
# this variable is used and neither bind_address nor port given, 
# then the default listener will not be started.
# The port number to listen on must be given. Optionally, an ip 
# address or host name may be supplied as a second argument. In 
# this case, mosquitto will attempt to bind the listener to that 
# address and so restrict access to the associated network and 
# interface. By default, mosquitto will listen on all interfaces.
# Note that for a websockets listener it is not possible to bind to a host
# name.
# listener port-number [ip address/host name]
#listener

# The maximum number of client connections to allow. This is 
# a per listener setting.
# Default is -1, which means unlimited connections.
# Note that other process limits mean that unlimited connections 
# are not really possible. Typically the default maximum number of 
# connections possible is around 1024.
#max_connections -1

# The listener can be restricted to operating within a topic hierarchy using
# the mount_point option. This is achieved be prefixing the mount_point string
# to all topics for any clients connected to this listener. This prefixing only
# happens internally to the broker; the client will not see the prefix.
#mount_point

# Choose the protocol to use when listening.
# This can be either mqtt or websockets.
# Certificate based TLS may be used with websockets, except that only the
# cafile, certfile, keyfile and ciphers options are supported.
#protocol mqtt

# When a listener is using the websockets protocol, it is possible to serve
# http data as well. Set http_dir to a directory which contains the files you
# wish to serve. If this option is not specified, then no normal http
# connections will be possible.
#http_dir

# Set use_username_as_clientid to true to replace the clientid that a client
# connected with with its username. This allows authentication to be tied to
# the clientid, which means that it is possible to prevent one client
# disconnecting another by using the same clientid.
# If a client connects with no username it will be disconnected as not
# authorised when this option is set to true.
# Do not use in conjunction with clientid_prefixes.
# See also use_identity_as_username.
#use_username_as_clientid

# -----------------------------------------------------------------
# Certificate based SSL/TLS support
# -----------------------------------------------------------------
# The following options can be used to enable certificate based SSL/TLS support
# for this listener. Note that the recommended port for MQTT over TLS is 8883,
# but this must be set manually.
#
# See also the mosquitto-tls man page and the "Pre-shared-key based SSL/TLS
# support" section. Only one of certificate or PSK encryption support can be
# enabled for any listener.

# At least one of cafile or capath must be defined to enable certificate based
# TLS encryption. They both define methods of accessing the PEM encoded
# Certificate Authority certificates that have signed your server certificate
# and that you wish to trust.
# cafile defines the path to a file containing the CA certificates.
# capath defines a directory that will be searched for files
# containing the CA certificates. For capath to work correctly, the
# certificate files must have ".crt" as the file ending and you must run
# "openssl rehash <path to capath>" each time you add/remove a certificate.
#cafile
#capath

# Path to the PEM encoded server certificate.
#certfile

# Path to the PEM encoded keyfile.
#keyfile

# By default an TLS enabled listener will operate in a similar fashion to a
# https enabled web server, in that the server has a certificate signed by a CA
# and the client will verify that it is a trusted certificate. The overall aim
# is encryption of the network traffic. By setting require_certificate to true,
# the client must provide a valid certificate in order for the network
# connection to proceed. This allows access to the broker to be controlled
# outside of the mechanisms provided by MQTT.
#require_certificate false

# If require_certificate is true, you may set use_identity_as_username to true
# to use the CN value from the client certificate as a username. If this is
# true, the password_file option will not be used for this listener.
#use_identity_as_username false

# If you have require_certificate set to true, you can create a certificate
# revocation list file to revoke access to particular client certificates. If
# you have done this, use crlfile to point to the PEM encoded revocation file.
#crlfile

# If you wish to control which encryption ciphers are used, use the ciphers
# option. The list of available ciphers can be optained using the "openssl
# ciphers" command and should be provided in the same format as the output of
# that command.
#ciphers

# -----------------------------------------------------------------
# Pre-shared-key based SSL/TLS support
# -----------------------------------------------------------------
# The following options can be used to enable PSK based SSL/TLS support for
# this listener. Note that the recommended port for MQTT over TLS is 8883, but
# this must be set manually.
#
# See also the mosquitto-tls man page and the "Certificate based SSL/TLS
# support" section. Only one of certificate or PSK encryption support can be
# enabled for any listener.

# The psk_hint option enables pre-shared-key support for this listener and also
# acts as an identifier for this listener. The hint is sent to clients and may
# be used locally to aid authentication. The hint is a free form string that
# doesn't have much meaning in itself, so feel free to be creative.
# If this option is provided, see psk_file to define the pre-shared keys to be
# used or create a security plugin to handle them.
#psk_hint

# Set use_identity_as_username to have the psk identity sent by the client used
# as its username. Authentication will be carried out using the PSK rather than
# the MQTT username/password and so password_file will not be used for this
# listener.
#use_identity_as_username false

# When using PSK, the encryption ciphers used will be chosen from the list of
# available PSK ciphers. If you want to control which ciphers are available,
# use the "ciphers" option.  The list of available ciphers can be optained
# using the "openssl ciphers" command and should be provided in the same format
# as the output of that command.
#ciphers

# =================================================================
# Persistence
# =================================================================

# If persistence is enabled, save the in-memory database to disk 
# every autosave_interval seconds. If set to 0, the persistence 
# database will only be written when mosquitto exits. See also
# autosave_on_changes.
# Note that writing of the persistence database can be forced by 
# sending mosquitto a SIGUSR1 signal.
#autosave_interval 1800

# If true, mosquitto will count the number of subscription changes, retained
# messages received and queued messages and if the total exceeds
# autosave_interval then the in-memory database will be saved to disk.
# If false, mosquitto will save the in-memory database to disk by treating
# autosave_interval as a time in seconds.
#autosave_on_changes false

# Save persistent message data to disk (true/false).
# This saves information about all messages, including 
# subscriptions, currently in-flight messages and retained 
# messages.
# retained_persistence is a synonym for this option.
#persistence false

# The filename to use for the persistent database, not including 
# the path.
#persistence_file mosquitto.db

# Location for persistent database. Must include trailing /
# Default is an empty string (current directory).
# Set to e.g. /var/lib/mosquitto/ if running as a proper service on Linux or
# similar.
#persistence_location

# =================================================================
# Logging
# =================================================================

# Places to log to. Use multiple log_dest lines for multiple 
# logging destinations.
# Possible destinations are: stdout stderr syslog topic file
#
# stdout and stderr log to the console on the named output.
#
# syslog uses the userspace syslog facility which usually ends up 
# in /var/log/messages or similar.
#
# topic logs to the broker topic '$SYS/broker/log/<severity>', 
# where severity is one of D, E, W, N, I, M which are debug, error, 
# warning, notice, information and message. Message type severity is used by
# the subscribe/unsubscribe log_types and publishes log messages to
# $SYS/broker/log/M/susbcribe or $SYS/broker/log/M/unsubscribe.
#
# The file destination requires an additional parameter which is the file to be
# logged to, e.g. "log_dest file /var/log/mosquitto.log". The file will be
# closed and reopened when the broker receives a HUP signal. Only a single file
# destination may be configured.
#
# Note that if the broker is running as a Windows service it will default to
# "log_dest none" and neither stdout nor stderr logging is available.
# Use "log_dest none" if you wish to disable logging.
#log_dest stderr

# If using syslog logging (not on Windows), messages will be logged to the
# "daemon" facility by default. Use the log_facility option to choose which of
# local0 to local7 to log to instead. The option value should be an integer
# value, e.g. "log_facility 5" to use local5.
#log_facility

# Types of messages to log. Use multiple log_type lines for logging
# multiple types of messages.
# Possible types are: debug, error, warning, notice, information, 
# none, subscribe, unsubscribe, websockets, all.
# Note that debug type messages are for decoding the incoming/outgoing
# network packets. They are not logged in "topics".
#log_type error
#log_type warning
#log_type notice
#log_type information

# Change the websockets logging level. This is a global option, it is not
# possible to set per listener. This is an integer that is interpreted by
# libwebsockets as a bit mask for its lws_log_levels enum. See the
# libwebsockets documentation for more details. "log_type websockets" must also
# be enabled.
#websockets_log_level 0

# If set to true, client connection and disconnection messages will be included
# in the log.
#connection_messages true

# If set to true, add a timestamp value to each log message.
#log_timestamp true

# =================================================================
# Security
# =================================================================

# If set, only clients that have a matching prefix on their 
# clientid will be allowed to connect to the broker. By default, 
# all clients may connect.
# For example, setting "secure-" here would mean a client "secure-
# client" could connect but another with clientid "mqtt" couldn't.
#clientid_prefixes

# Boolean value that determines whether clients that connect 
# without providing a username are allowed to connect. If set to 
# false then a password file should be created (see the 
# password_file option) to control authenticated client access. 
#
# Defaults to true if no other security options are set. If any other
# authentication options are set, then allow_anonymous defaults to false.
#
#allow_anonymous true

# -----------------------------------------------------------------
# Default authentication and topic access control
# -----------------------------------------------------------------

# Control access to the broker using a password file. This file can be
# generated using the mosquitto_passwd utility. If TLS support is not compiled
# into mosquitto (it is recommended that TLS support should be included) then
# plain text passwords are used, in which case the file should be a text file
# with lines in the format:
# username:password
# The password (and colon) may be omitted if desired, although this 
# offers very little in the way of security.
# 
# See the TLS client require_certificate and use_identity_as_username options
# for alternative authentication options. If an auth_plugin is used as well as
# password_file, the auth_plugin check will be made first.
#password_file

# Access may also be controlled using a pre-shared-key file. This requires
# TLS-PSK support and a listener configured to use it. The file should be text
# lines in the format:
# identity:key
# The key should be in hexadecimal format without a leading "0x".
# If an auth_plugin is used as well, the auth_plugin check will be made first.
#psk_file

# Control access to topics on the broker using an access control list
# file. If this parameter is defined then only the topics listed will
# have access.
# If the first character of a line of the ACL file is a # it is treated as a
# comment.
# Topic access is added with lines of the format:
#
# topic [read|write|readwrite] <topic>
# 
# The access type is controlled using "read", "write" or "readwrite". This
# parameter is optional (unless <topic> contains a space character) - if not
# given then the access is read/write.  <topic> can contain the + or #
# wildcards as in subscriptions.
# 
# The first set of topics are applied to anonymous clients, assuming
# allow_anonymous is true. User specific topic ACLs are added after a 
# user line as follows:
#
# user <username>
#
# The username referred to here is the same as in password_file. It is
# not the clientid.
#
#
# If is also possible to define ACLs based on pattern substitution within the
# topic. The patterns available for substition are:
#
# %c to match the client id of the client
# %u to match the username of the client
#
# The substitution pattern must be the only text for that level of hierarchy.
#
# The form is the same as for the topic keyword, but using pattern as the
# keyword.
# Pattern ACLs apply to all users even if the "user" keyword has previously
# been given.
#
# If using bridges with usernames and ACLs, connection messages can be allowed
# with the following pattern:
# pattern write $SYS/broker/connection/%c/state
#
# pattern [read|write|readwrite] <topic>
#
# Example:
#
# pattern write sensor/%u/data
#
# If an auth_plugin is used as well as acl_file, the auth_plugin check will be
# made first.
#acl_file

# -----------------------------------------------------------------
# External authentication and topic access plugin options
# -----------------------------------------------------------------

# External authentication and access control can be supported with the
# auth_plugin option. This is a path to a loadable plugin. See also the
# auth_opt_* options described below. 
#
# The auth_plugin option can be specified multiple times to load multiple
# plugins. The plugins will be processed in the order that they are specified
# here. If the auth_plugin option is specified alongside either of
# password_file or acl_file then the plugin checks will be made first.
#
#auth_plugin

# If the auth_plugin option above is used, define options to pass to the
# plugin here as described by the plugin instructions. All options named
# using the format auth_opt_* will be passed to the plugin, for example:
#
# auth_opt_db_host
# auth_opt_db_port 
# auth_opt_db_username
# auth_opt_db_password


# =================================================================
# Bridges
# =================================================================

# A bridge is a way of connecting multiple MQTT brokers together.
# Create a new bridge using the "connection" option as described below. Set
# options for the bridges using the remaining parameters. You must specify the
# address and at least one topic to subscribe to.
#
# Each connection must have a unique name.
#
# The address line may have multiple host address and ports specified. See
# below in the round_robin description for more details on bridge behaviour if
# multiple addresses are used. Note that if you use an IPv6 address, then you
# are required to specify a port.
#
# The direction that the topic will be shared can be chosen by 
# specifying out, in or both, where the default value is out. 
# The QoS level of the bridged communication can be specified with the next
# topic option. The default QoS level is 0, to change the QoS the topic
# direction must also be given.
#
# The local and remote prefix options allow a topic to be remapped when it is
# bridged to/from the remote broker. This provides the ability to place a topic
# tree in an appropriate location. 
#
# For more details see the mosquitto.conf man page.
#
# Multiple topics can be specified per connection, but be careful 
# not to create any loops.
#
# If you are using bridges with cleansession set to false (the default), then
# you may get unexpected behaviour from incoming topics if you change what
# topics you are subscribing to. This is because the remote broker keeps the
# subscription for the old topic. If you have this problem, connect your bridge
# with cleansession set to true, then reconnect with cleansession set to false
# as normal.
#connection <name>
#address <host>[:<port>] [<host>[:<port>]]
#topic <topic> [[[out | in | both] qos-level] local-prefix remote-prefix]

# Set the version of the MQTT protocol to use with for this bridge. Can be one
# of mqttv311 or mqttv11. Defaults to mqttv311.
#bridge_protocol_version mqttv311

# If a bridge has topics that have "out" direction, the default behaviour is to
# send an unsubscribe request to the remote broker on that topic. This means
# that changing a topic direction from "in" to "out" will not keep receiving
# incoming messages. Sending these unsubscribe requests is not always
# desirable, setting bridge_attempt_unsubscribe to false will disable sending
# the unsubscribe request.
#bridge_attempt_unsubscribe true

# If the bridge has more than one address given in the address/addresses
# configuration, the round_robin option defines the behaviour of the bridge on
# a failure of the bridge connection. If round_robin is false, the default
# value, then the first address is treated as the main bridge connection. If
# the connection fails, the other secondary addresses will be attempted in
# turn. Whilst connected to a secondary bridge, the bridge will periodically
# attempt to reconnect to the main bridge until successful.
# If round_robin is true, then all addresses are treated as equals. If a
# connection fails, the next address will be tried and if successful will
# remain connected until it fails
#round_robin false

# Set the client id to use on the remote end of this bridge connection. If not
# defined, this defaults to 'name.hostname' where name is the connection name
# and hostname is the hostname of this computer.
# This replaces the old "clientid" option to avoid confusion. "clientid"
# remains valid for the time being.
#remote_clientid

# Set the clientid to use on the local broker. If not defined, this defaults to
# 'local.<clientid>'. If you are bridging a broker to itself, it is important
# that local_clientid and clientid do not match.
#local_clientid

# Set the clean session variable for this bridge.
# When set to true, when the bridge disconnects for any reason, all 
# messages and subscriptions will be cleaned up on the remote 
# broker. Note that with cleansession set to true, there may be a 
# significant amount of retained messages sent when the bridge 
# reconnects after losing its connection.
# When set to false, the subscriptions and messages are kept on the 
# remote broker, and delivered when the bridge reconnects.
#cleansession false

# If set to true, publish notification messages to the local and remote brokers
# giving information about the state of the bridge connection. Retained
# messages are published to the topic $SYS/broker/connection/<clientid>/state
# unless the notification_topic option is used.
# If the message is 1 then the connection is active, or 0 if the connection has
# failed.
#notifications true

# Choose the topic on which notification messages for this bridge are
# published. If not set, messages are published on the topic
# $SYS/broker/connection/<clientid>/state
#notification_topic 

# Set the keepalive interval for this bridge connection, in 
# seconds.
#keepalive_interval 60

# Set the start type of the bridge. This controls how the bridge starts and
# can be one of three types: automatic, lazy and once. Note that RSMB provides
# a fourth start type "manual" which isn't currently supported by mosquitto.
#
# "automatic" is the default start type and means that the bridge connection
# will be started automatically when the broker starts and also restarted
# after a short delay (30 seconds) if the connection fails.
#
# Bridges using the "lazy" start type will be started automatically when the
# number of queued messages exceeds the number set with the "threshold"
# parameter. It will be stopped automatically after the time set by the
# "idle_timeout" parameter. Use this start type if you wish the connection to
# only be active when it is needed.
#
# A bridge using the "once" start type will be started automatically when the
# broker starts but will not be restarted if the connection fails.
#start_type automatic

# Set the amount of time a bridge using the automatic start type will wait
# until attempting to reconnect.  Defaults to 30 seconds.
#restart_timeout 30

# Set the amount of time a bridge using the lazy start type must be idle before
# it will be stopped. Defaults to 60 seconds.
#idle_timeout 60

# Set the number of messages that need to be queued for a bridge with lazy
# start type to be restarted. Defaults to 10 messages.
# Must be less than max_queued_messages.
#threshold 10

# If try_private is set to true, the bridge will attempt to indicate to the
# remote broker that it is a bridge not an ordinary client. If successful, this
# means that loop detection will be more effective and that retained messages
# will be propagated correctly. Not all brokers support this feature so it may
# be necessary to set try_private to false if your bridge does not connect
# properly.
#try_private true

# Set the username to use when connecting to a broker that requires
# authentication.
# This replaces the old "username" option to avoid confusion. "username"
# remains valid for the time being.
#remote_username

# Set the password to use when connecting to a broker that requires
# authentication. This option is only used if remote_username is also set.
# This replaces the old "password" option to avoid confusion. "password"
# remains valid for the time being.
#remote_password

# -----------------------------------------------------------------
# Certificate based SSL/TLS support
# -----------------------------------------------------------------
# Either bridge_cafile or bridge_capath must be defined to enable TLS support
# for this bridge.
# bridge_cafile defines the path to a file containing the
# Certificate Authority certificates that have signed the remote broker
# certificate.
# bridge_capath defines a directory that will be searched for files containing
# the CA certificates. For bridge_capath to work correctly, the certificate
# files must have ".crt" as the file ending and you must run "openssl rehash
# <path to capath>" each time you add/remove a certificate.
#bridge_cafile
#bridge_capath

# Path to the PEM encoded client certificate, if required by the remote broker.
#bridge_certfile

# Path to the PEM encoded client private key, if required by the remote broker.
#bridge_keyfile

# When using certificate based encryption, bridge_insecure disables
# verification of the server hostname in the server certificate. This can be
# useful when testing initial server configurations, but makes it possible for
# a malicious third party to impersonate your server through DNS spoofing, for
# example. Use this option in testing only. If you need to resort to using this
# option in a production environment, your setup is at fault and there is no
# point using encryption.
#bridge_insecure false

# -----------------------------------------------------------------
# PSK based SSL/TLS support
# -----------------------------------------------------------------
# Pre-shared-key encryption provides an alternative to certificate based
# encryption. A bridge can be configured to use PSK with the bridge_identity
# and bridge_psk options. These are the client PSK identity, and pre-shared-key
# in hexadecimal format with no "0x". Only one of certificate and PSK based
# encryption can be used on one
# bridge at once.
#bridge_identity
#bridge_psk


# =================================================================
# External config files
# =================================================================

# External configuration files may be included by using the 
# include_dir option. This defines a directory that will be searched
# for config files. All files that end in '.conf' will be loaded as
# a configuration file. It is best to have this as the last option
# in the main file. This option will only be processed from the main
# configuration file. The directory specified must not contain the 
# main configuration file.
# Files within include_dir will be loaded sorted in case-sensitive
# alphabetical order, with capital letters ordered first. If this option is
# given multiple times, all of the files from the first instance will be
# processed before the next instance. See the man page for examples.
#include_dir

# =================================================================
# rsmb options - unlikely to ever be supported
# =================================================================

#ffdc_output
#max_log_entries
#trace_level
#trace_output

Die beiden hier interessanten Abschnitte sind 'Persistence' und 'Logging'.

Persistence

(NB: Persistenz (von lateinisch persistere „durch, über (eine Zeit) hinweg bleiben“))

Das Verhalten des Brokers lässt sich durch 5 Optionen beeinflussen:

  1. autosave_interval <sekunden> oder <anzahl>
  2. autosave_on_changes <true|false>
  3. persistence <true|false>
  4. persistence_file mosquitto.db
  5. persistence_location

Mit autosave_interval kann man die Anzahl der Sekunden als Zeitspanne angeben nach der eine Speicherung der 'in-memory database' auf einen Datenträger erfolgt. Die Information die hier latent vorhanden ist, dass der Broker seine Meldungen alle im Speicher hält. Der default-Wert ist hier nicht angegeben. Ist <sekunden> = 0 dann wird die 'inmemorydb' nur nach dem Stoppen des Brokers geschrieben. Ein

kill -SIGUSR1 <mosquitto-pid>

erzwingt ebenfalls eine Speicherung der 'in-memory database' auf einen Datenträger.

Abhängig von autosave_on_changes wechselt autosave_interval die Bedeutung. Bei autosave_on_changes false werden mit autosave_interval die Anzahl der Sekunden bis zur nächsten Sicherung angegeben. Mit autosave_on_changes true werden mit autosave_interval die Anzahl der subscription changes, retained messages received and queued messages angegeben, die nach Überschreitung einen auch eine Speicherung der 'in-memory database' auslöst.

Mit persistence true kann man wohl das Speichern grundsätzlich einschalten. Damit werden vermutlich die autosave-Optionen hinfällig und persistence_file und persistence_location erhalten eine Bedeutung.

Um herauszufinden, ob das alles so funktioniert wie ich mir das vorstelle habe ich folgende Optionen gesetzt.

persistence true
persistence_file mosquitto.db
persistence_location /var/lib/mosquitto/

Nach dem Neustart des Brokers

systemctl restart mosquitto

und dem Absetzen eines Publish bliebt allerdings das Verzeichnis /var/lib/mosquitto/ leer:-( Erst ein

kill -SIGUSR1 <mosquitto-pid>

brachte eine mosquitto.db zum Vorschein, die aber leer war.

Logging

Client als Debughilfe

... to be continued

Mosquitto Clients

mosquitto_pub

mosquitto_pub is a simple mqtt client that will publish a message on a single topic and exit. mosquitto_pub version 1.6.9 running on libmosquitto 1.6.9.

MOSQUITTO_PUB(1)

NAME

      mosquitto_pub - an MQTT version 5/3.1.1/3.1 client for publishing simple messages

SYNOPSIS

      mosquitto_pub {[-h hostname] [-p port-number] [-u username] [-P password] -t message-topic...  | -L URL} 
                    [-A bind-address] [-c] [-d] [-D command identifier value]
                    [-i client-id] [-I client-id-prefix] [-k keepalive-time] [-q message-QoS] [--quiet] [-r] [--repeat count]
                    [--repeat-delay seconds] [-S] {-f file | -l | -m message
                    | -n | -s} [--will-topic topic [--will-payload payload] [--will-qos qos] [--will-retain]]
                    [[{--cafile file | --capath dir} [--cert file] [--key file] [--ciphers ciphers] [--tls-version version]
                    [--tls-alpn protocol] [--tls-engine engine] [--keyform {pem | engine}] 
                    [--tls-engine-kpass-sha1 kpass-sha1] [--insecure]]
                    | [--psk hex-key --psk-identity identity [--ciphers ciphers] [--tls-version version]]] [--proxy socks-url] 
                    [-V protocol-version]
      mosquitto_pub [--help]
                    Usage: mosquitto_pub {[-h host] [-p port] [-u username] [-P password] -t topic | -L URL}
                    {-f file | -l | -n | -m message}
                    [-c] [-k keepalive] [-q qos] [-r] [--repeat N] [--repeat-delay time]
                    [-A bind_address]
                    [-i id] [-I id_prefix]
                    [-d] [--quiet]
                    [-M max_inflight]
                    [-u username [-P password]]
                    [--will-topic [--will-payload payload] [--will-qos qos] [--will-retain]]
                    [{--cafile file | --capath dir} [--cert file] [--key file]
                      [--ciphers ciphers] [--insecure]
                      [--tls-alpn protocol]
                      [--tls-engine engine] [--keyform keyform] [--tls-engine-kpass-sha1]]
                    [--psk hex-key --psk-identity identity [--ciphers ciphers]]
                    [--proxy socks-url]
                    [--property command identifier value]
                    [-D command identifier value]
      mosquitto_pub --help
-A : bind the outgoing socket to this host/ip address. Use to control which interface
     the client communicates over.
-d : enable debug messages.
-D : Define MQTT v5 properties. See the documentation for more details.
-f : send the contents of a file as the message.
-h : mqtt host to connect to. Defaults to localhost.
-i : id to use for this client. Defaults to mosquitto_pub_ appended with the process id.
-I : define the client id as id_prefix appended with the process id. Useful for when the
     broker is using the clientid_prefixes option.
-k : keep alive in seconds for this client. Defaults to 60.
-L : specify user, password, hostname, port and topic as a URL in the form:
     mqtt(s)://[username[:password]@]host[:port]/topic
-l : read messages from stdin, sending a separate message for each line.
-m : message payload to send.
-M : the maximum inflight messages for QoS 1/2..
-n : send a null (zero length) message.
-p : network port to connect to. Defaults to 1883 for plain MQTT and 8883 for MQTT over TLS.
-P : provide a password
-q : quality of service level to use for all messages. Defaults to 0.
-r : message should be retained.
-s : read message from stdin, sending the entire input as a message.
-t : mqtt topic to publish to.
-u : provide a username
-V : specify the version of the MQTT protocol to use when connecting.
     Can be mqttv5, mqttv311 or mqttv31. Defaults to mqttv311.
--help : display this message.
--repeat : if publish mode is -f, -m, or -s, then repeat the publish N times.
--repeat-delay : if using --repeat, wait time seconds between publishes. Defaults to 0.
--quiet : don't print error messages.
--will-payload : payload for the client Will, which is sent by the broker in case of
                 unexpected disconnection. If not given and will-topic is set, a zero
                 length message will be sent.
--will-qos : QoS level for the client Will.
--will-retain : if given, make the client Will retained.
--will-topic : the topic on which to publish the client Will.
--cafile : path to a file containing trusted CA certificates to enable encrypted
           communication.
--capath : path to a directory containing trusted CA certificates to enable encrypted
           communication.
--cert : client certificate for authentication, if required by server.
--key : client private key for authentication, if required by server.
--keyform : keyfile type, can be either "pem" or "engine".
--ciphers : openssl compatible list of TLS ciphers to support.
--tls-version : TLS protocol version, can be one of tlsv1.3 tlsv1.2 or tlsv1.1.
                Defaults to tlsv1.2 if available.
--insecure : do not check that the server certificate hostname matches the remote
             hostname. Using this option means that you cannot be sure that the
             remote host is the server you wish to connect to and so is insecure.
             Do not use this option in a production environment.
--tls-engine : If set, enables the use of a TLS engine device.
--tls-engine-kpass-sha1 : SHA1 of the key password to be used with the selected SSL engine.
--psk : pre-shared-key in hexadecimal (no leading 0x) to enable TLS-PSK mode.
--psk-identity : client identity string for TLS-PSK mode.
--proxy : SOCKS5 proxy URL of the form:
          socks5h://[username[:password]@]hostname[:port]
          Only "none" and "username" authentication is supported.

See https://mosquitto.org/ for more information. DESCRIPTION

      mosquitto_pub is a simple MQTT version 5/3.1.1 client that will publish a single message on a topic and exit.

ENCRYPTED CONNECTIONS

      mosquitto_pub supports TLS encrypted connections. It is strongly recommended that you use an encrypted connection for anything more than the most basic setup.
      To enable TLS connections when using x509 certificates, one of either --cafile or --capath must be provided as an option.
      To enable TLS connections when using TLS-PSK, you must use the --psk and the --psk-identity options.

OPTIONS

      The options below may be given on the command line, but may also be placed in a config file located at $XDG_CONFIG_HOME/mosquitto_pub or $HOME/.config/mosquitto_pub with one
      pair of -option value per line. The values in the config file will be used as defaults and can be overridden by using the command line. The exceptions to this are the message
      type options, of which only one can be specified. Note also that currently some options cannot be negated, e.g.  -S. Config file lines that have a # as the first character are
      treated as comments and not processed any further.
      -A
          Bind the outgoing connection to a local ip address/hostname. Use this argument if you need to restrict network communication to a particular interface.
      -c, --disable-clean-session
          Disable the 'clean session' flag. This means that all of the subscriptions for the client will be maintained after it disconnects, along with subsequent QoS 1 and QoS 2
          messages that arrive. When the client reconnects, it will receive all of the queued messages.
          If using this option, the client id must be set manually with --id
      --cafile
          Define the path to a file containing PEM encoded CA certificates that are trusted. Used to enable SSL communication.
          See also --capath
      --capath
          Define the path to a directory containing PEM encoded CA certificates that are trusted. Used to enable SSL communication.
          For --capath to work correctly, the certificate files must have ".crt" as the file ending and you must run "openssl rehash <path to capath>" each time you add/remove a
          certificate.
          See also --cafile
      --cert
          Define the path to a file containing a PEM encoded certificate for this client, if required by the server.
          See also --key.
      --ciphers
          An openssl compatible list of TLS ciphers to support in the client. See ciphers(1) for more information.
      -d, --debug
          Enable debug messages.
      -D, --property
          Use an MQTT v5 property with this publish. If you use this option, the client will be set to be an MQTT v5 client. This option has two forms:
          -D command identifier value
          -D command identifier name value
          command is the MQTT command/packet identifier and can be one of CONNECT, PUBLISH, PUBREL, DISCONNECT, AUTH, or WILL. The properties available for each command are listed in
          the Properties section.
          identifier is the name of the property to add. This is as described in the specification, but with '-' as a word separator. For example: payload-format-indicator. More
          details are in the Properties section.
          value is the value of the property to add, with a data type that is property specific.
          name is only used for the user-property property as the first of the two strings in the string pair. In that case, value is the second of the strings in the pair.
      -f, --file
          Send the contents of a file as the message.
      --help
          Display usage information.
      -h, --host
          Specify the host to connect to. Defaults to localhost.
      -i, --id
          The id to use for this client. If not given, a client id will be generated depending on the MQTT version being used. For v3.1.1/v3.1, the client generates a client id in
          the format mosq-XXXXXXXXXXXXXXXXXX, where the X are replaced with random alphanumeric characters. For v5.0, the client sends a zero length client id, and the server will
          generate a client id for the client.
          This option cannot be used at the same time as the --id-prefix argument.
      -I, --id-prefix
          Provide a prefix that the client id will be built from by appending the process id of the client. This is useful where the broker is using the clientid_prefixes option.
          Cannot be used at the same time as the --id argument.
      --insecure
          When using certificate based encryption, this option disables verification of the server hostname in the server certificate. This can be useful when testing initial server
          configurations but makes it possible for a malicious third party to impersonate your server through DNS spoofing, for example. Use this option in testing only. If you need
          to resort to using this option in a production environment, your setup is at fault and there is no point using encryption.
      -k, --keepalive
          The number of seconds between sending PING commands to the broker for the purposes of informing it we are still connected and functioning. Defaults to 60 seconds.
      --key
          Define the path to a file containing a PEM encoded private key for this client, if required by the server.
          See also --cert.
      --keyform
          Specifies the type of private key in use when making TLS connections.. This can be "pem" or "engine". This parameter is useful when a TPM module is being used and the
          private key has been created with it. Defaults to "pem", which means normal private key files are used.
          See also --tls-engine.
      -L, --url
          Specify specify user, password, hostname, port and topic at once as a URL. The URL must be in the form: mqtt(s)://[username[:password]@]host[:port]/topic
          If the scheme is mqtt:// then the port defaults to 1883. If the scheme is mqtts:// then the port defaults to 8883.
      -l, --stdin-line
          Send messages read from stdin, splitting separate lines into separate messages.
      -m, --message
          Send a single message from the command line.
      -n, --null-message
          Send a null (zero length) message.
      -p, --port
          Connect to the port specified. If not given, the default of 1883 for plain MQTT or 8883 for MQTT over TLS will be used.
      -P, --pw
          Provide a password to be used for authenticating with the broker. Using this argument without also specifying a username is invalid when using MQTT v3.1 or v3.1.1. See also
          the --username option.
      --proxy
          Specify a SOCKS5 proxy to connect through. "None" and "username" authentication types are supported. The socks-url must be of the form
          socks5h://[username[:password]@]host[:port]. The protocol prefix socks5h means that hostnames are resolved by the proxy. The symbols %25, %3A and %40 are URL decoded into
          %, : and @ respectively, if present in the username or password.
          If username is not given, then no authentication is attempted. If the port is not given, then the default of 1080 is used.
          More SOCKS versions may be available in the future, depending on demand, and will use different protocol prefixes as described in curl(1).
      --psk
          Provide the hexadecimal (no leading 0x) pre-shared-key matching the one used on the broker to use TLS-PSK encryption support.  --psk-identity must also be provided to
          enable TLS-PSK.
      --psk-identity
          The client identity to use with TLS-PSK support. This may be used instead of a username if the broker is configured to do so.
      -q, --qos
          Specify the quality of service to use for the message, from 0, 1 and 2. Defaults to 0.
      --quiet
          If this argument is given, no runtime errors will be printed. This excludes any error messages given in case of invalid user input (e.g. using --port without a port).
      -r, --retain
          If retain is given, the message will be retained as a "last known good" value on the broker. See mqtt(7) for more information.
      --repeat
          If the publish mode is-m, -f, or -s (i.e. the modes where only a single message is sent), then --repeat can be used to specify that the message will be published multiple
          times.
          See also --repeat-delay.
      --repeat-delay
          If using --repeat, then the default behaviour is to publish repeated messages as soon as the previous message is delivered. Use --repeat-delay to specify the number of
          seconds to wait after the previous message was delivered before publishing the next. Does not need to be an integer number of seconds.
          Note that there is no guarantee as to the actual interval between messages, this option simply defines the minimum time from delivery of one message to the start of the
          publish of the next.
      -s, --stdin-file
          Send a message read from stdin, sending the entire content as a single message.
      -S
          Use SRV lookups to determine which host to connect to. Performs lookups to _mqtt._tcp.<host> when used in conjunction with -h, otherwise uses _mqtt._tcp.<local dns domain>.
      -t, --topic
          The MQTT topic on which to publish the message. See mqtt(7) for more information on MQTT topics.
      --tls-alpn
          Provide a protocol to use when connecting to a broker that has multiple protocols available on a single port, e.g. MQTT and WebSockets.
      --tls-engine
          A valid openssl engine id. These can be listed with openssl engine command.
          See also --keyform.
      --tls-engine-kpass-sha1
          SHA1 of the private key password when using an TLS engine. Some TLS engines such as the TPM engine may require the use of a password in order to be accessed. This option
          allows a hex encoded SHA1 hash of the password to the engine directly, instead of the user being prompted for the password.
          See also --tls-engine.
      --tls-version
          Choose which TLS protocol version to use when communicating with the broker. Valid options are tlsv1.3, tlsv1.2 and tlsv1.1. The default value is tlsv1.2. Must match the
          protocol version used by the broker.
      -u, --username
          Provide a username to be used for authenticating with the broker. See also the --pw argument.
      -V, --protocol-version
          Specify which version of the MQTT protocol should be used when connecting to the rmeote broker. Can be 5, 311, 31, or the more verbose mqttv5, mqttv311, or mqttv31.
          Defaults to 311.
      --will-payload
          Specify a message that will be stored by the broker and sent out if this client disconnects unexpectedly. This must be used in conjunction with --will-topic.
      --will-qos
          The QoS to use for the Will. Defaults to 0. This must be used in conjunction with --will-topic.
      --will-retain
          If given, if the client disconnects unexpectedly the message sent out will be treated as a retained message. This must be used in conjunction with --will-topic.
      --will-topic
          The topic on which to send a Will, in the event that the client disconnects unexpectedly.

WILLS

      mosquitto_sub can register a message with the broker that will be sent out if it disconnects unexpectedly. See mqtt(7) for more information.
      The minimum requirement for this is to use --will-topic to specify which topic the will should be sent out on. This will result in a non-retained, zero length message with QoS
      0.
      Use the --will-retain, --will-payload and --will-qos arguments to modify the other will parameters.

PROPERTIES

      The -D / --property option allows adding properties to different stages of the mosquitto_pub run. The properties supported for each command are as follows:
  Connect
      ·   authentication-data (binary data - note treated as a string in mosquitto_pub)
      ·   authentication-method (UTF-8 string pair)
      ·   maximum-packet-size (32-bit unsigned integer)
      ·   receive-maximum (16-bit unsigned integer)
      ·   request-problem-information (8-bit unsigned integer)
      ·   request-response-information (8-bit unsigned integer)
      ·   session-expiry-interval (32-bit unsigned integer)
      ·   topic-alias-maximum (16-bit unsigned integer)
      ·   user-property (UTF-8 string pair)
  Publish
      ·   content-type (UTF-8 string)
      ·   correlation-data (binary data - note treated as a string in mosquitto_pub)
      ·   message-expiry-interval (32-bit unsigned integer)
      ·   payload-format-indicator (8-bit unsigned integer)
      ·   response-topic (UTF-8 string)
      ·   topic-alias (16-bit unsigned integer)
      ·   user-property (UTF-8 string pair)
  Disconnect
      ·   session-expiry-interval (32-bit unsigned integer)
      ·   user-property (UTF-8 string pair)
  Will properties
      ·   content-type (UTF-8 string)
      ·   correlation-data (binary data - note treated as a string in mosquitto_pub)
      ·   message-expiry-interval (32-bit unsigned integer)
      ·   payload-format-indicator (8-bit unsigned integer)
      ·   response-topic (UTF-8 string)
      ·   user-property (UTF-8 string pair)
      ·   will-delay-interval (32-bit unsigned integer)

EXAMPLES

      Publish temperature information to localhost with QoS 1:
      ·   mosquitto_pub -t sensors/temperature -m 32 -q 1
      Publish timestamp and temperature information to a remote host on a non-standard port and QoS 0:
      ·   mosquitto_pub -h 192.168.1.1 -p 1885 -t sensors/temperature -m "1266193804 32"
      Publish light switch status. Message is set to retained because there may be a long period of time between light switch events:
      ·   mosquitto_pub -r -t switches/kitchen_lights/status -m "on"
      Send the contents of a file in two ways:
      ·   mosquitto_pub -t my/topic -f ./data
      ·   mosquitto_pub -t my/topic -s < ./data
      Send parsed electricity usage data from a Current Cost meter, reading from stdin with one line/reading as one message:
      ·   read_cc128.pl | mosquitto_pub -t sensors/cc128 -l

FILES

      $XDG_CONFIG_HOME/mosquitto_pub, $HOME/.config/mosquitto_pub
          Configuration file for default options.

BUGS

      mosquitto bug information can be found at https://github.com/eclipse/mosquitto/issues

SEE ALSO

      mqtt(7), mosquitto_rr(1), mosquitto_sub(1), mosquitto(8), libmosquitto(3), mosquitto-tls(7)

AUTHOR

      Roger Light <roger@atchoo.org>

mosquitto_sub

Möchte man bei der Ausgabe eines abonnierten Wertes einen Zeitstempel dazu haben, habe ich im Netz ein paar Möglichkeiten gefunden:

mosquitto_sub works pretty well except it does not support to display a timestamp of the events.

The following “simple” command subscribes to all topics of the mosquitto MQTT server and executes the date command for each message.

mosquitto_sub -v -t /# | xargs -d$'\n' -L1 bash -c 'date "+%Y-%m-%d %T.%3N $0"'

Update: Thanks to Stewart C. Russell, who suggested to use ts from moreutils package, it can be achieved with a shorter expression:

mosquitto_sub -v -t /# | ts

mosquitto_sub -v -t /# -F "%I %t %p"

mosquitto_sub is a simple mqtt client that will subscribe to a set of topics and print all messages it receives. mosquitto_sub version 1.6.9 running on libmosquitto 1.6.9.

MOSQUITTO_SUB(1)

NAME

      mosquitto_sub - an MQTT version 5/3.1.1/3.1 client for subscribing to topics

SYNOPSIS

      mosquitto_sub {[-h hostname] [-p port-number] [-u username] [-P password] -t message-topic...  | -L URL [-t message-topic...] } [-A bind-address] [-c] [-C msg-count] [-d]
                    [-D command identifier value] [-E] [-i client-id] [-I client-id-prefix] [-k keepalive-time] [-N] [-q message-QoS] [--remove-retained] [-R | --retained-only]
                    [--retain-as-published] [-S] [-T filter-out...] [-U unsub-topic...] [-v] [-V protocol-version] [-W message-processing-timeout] [--proxy socks-url] [--quiet]
                    [--will-topic topic [--will-payload payload] [--will-qos qos] [--will-retain]]
                    [[{--cafile file | --capath dir} [--cert file] [--key file] [--tls-version version] [--tls-alpn protocol] [--tls-engine engine] [--keyform {pem | engine}] [--tls-engine-kpass-sha1 kpass-sha1] [--insecure]]
                    | [--psk hex-key --psk-identity identity [--tls-version version]]]
      mosquitto_sub [--help]
                    Usage: mosquitto_sub {[-h host] [-p port] [-u username] [-P password] -t topic | -L URL [-t topic]}
                    [-c] [-k keepalive] [-q qos]
                    [-C msg_count] [-E] [-R] [--retained-only] [--remove-retained] [-T filter_out] [-U topic ...]
                    [-F format]
                    [-W timeout_secs]
                    [-A bind_address]
                    [-i id] [-I id_prefix]
                    [-d] [-N] [--quiet] [-v]
                    [--will-topic [--will-payload payload] [--will-qos qos] [--will-retain]]
                    [{--cafile file | --capath dir} [--cert file] [--key file]
                      [--ciphers ciphers] [--insecure]
                      [--tls-alpn protocol]
                      [--tls-engine engine] [--keyform keyform] [--tls-engine-kpass-sha1]]
                    [--psk hex-key --psk-identity identity [--ciphers ciphers]]
                    [--proxy socks-url]
                    [-D command identifier value]
-A : bind the outgoing socket to this host/ip address. Use to control which interface
     the client communicates over.
-c : disable 'clean session' (store subscription and pending messages when client disconnects).
-C : disconnect and exit after receiving the 'msg_count' messages.
-d : enable debug messages.
-D : Define MQTT v5 properties. See the documentation for more details.
-E : Exit once all subscriptions have been acknowledged by the broker.
-F : output format.
-h : mqtt host to connect to. Defaults to localhost.
-i : id to use for this client. Defaults to mosquitto_sub_ appended with the process id.
-I : define the client id as id_prefix appended with the process id. Useful for when the
     broker is using the clientid_prefixes option.
-k : keep alive in seconds for this client. Defaults to 60.
-L : specify user, password, hostname, port and topic as a URL in the form:
     mqtt(s)://[username[:password]@]host[:port]/topic
-N : do not add an end of line character when printing the payload.
-p : network port to connect to. Defaults to 1883 for plain MQTT and 8883 for MQTT over TLS.
-P : provide a password
-q : quality of service level to use for the subscription. Defaults to 0.
-R : do not print stale messages (those with retain set).
-t : mqtt topic to subscribe to. May be repeated multiple times.
-T : topic string to filter out of results. May be repeated.
-u : provide a username
-U : unsubscribe from a topic. May be repeated.
-v : print published messages verbosely.
-V : specify the version of the MQTT protocol to use when connecting.
     Can be mqttv5, mqttv311 or mqttv31. Defaults to mqttv311.
-W : Specifies a timeout in seconds how long to process incoming MQTT messages.
--help : display this message.
--quiet : don't print error messages.
--retained-only : only handle messages with the retained flag set, and exit when the
                  first non-retained message is received.
--remove-retained : send a message to the server to clear any received retained messages
                    Use -T to filter out messages you do not want to be cleared.
--will-payload : payload for the client Will, which is sent by the broker in case of
                 unexpected disconnection. If not given and will-topic is set, a zero
                 length message will be sent.
--will-qos : QoS level for the client Will.
--will-retain : if given, make the client Will retained.
--will-topic : the topic on which to publish the client Will.
--cafile : path to a file containing trusted CA certificates to enable encrypted
           certificate based communication.
--capath : path to a directory containing trusted CA certificates to enable encrypted
           communication.
--cert : client certificate for authentication, if required by server.
--key : client private key for authentication, if required by server.
--keyform : keyfile type, can be either "pem" or "engine".
--ciphers : openssl compatible list of TLS ciphers to support.
--tls-version : TLS protocol version, can be one of tlsv1.3 tlsv1.2 or tlsv1.1.
                Defaults to tlsv1.2 if available.
--insecure : do not check that the server certificate hostname matches the remote
             hostname. Using this option means that you cannot be sure that the
             remote host is the server you wish to connect to and so is insecure.
             Do not use this option in a production environment.
--tls-engine : If set, enables the use of a SSL engine device.
--tls-engine-kpass-sha1 : SHA1 of the key password to be used with the selected SSL engine.
--psk : pre-shared-key in hexadecimal (no leading 0x) to enable TLS-PSK mode.
--psk-identity : client identity string for TLS-PSK mode.
--proxy : SOCKS5 proxy URL of the form:
          socks5h://[username[:password]@]hostname[:port]
          Only "none" and "username" authentication is supported.

See https://mosquitto.org/ for more information.

DESCRIPTION

      mosquitto_sub is a simple MQTT version 5/3.1.1 client that will subscribe to topics and print the messages that it receives.
      In addition to subscribing to topics, mosquitto_sub can filter out received messages so they are not printed (see the -T option) or unsubscribe from topics (see the -U option).
      Unsubscribing from topics is useful for clients connecting with clean session set to false.

ENCRYPTED CONNECTIONS

      mosquitto_sub supports TLS encrypted connections. It is strongly recommended that you use an encrypted connection for anything more than the most basic setup.
      To enable TLS connections when using x509 certificates, one of either --cafile or --capath must be provided as an option.
      To enable TLS connections when using TLS-PSK, you must use the --psk and the --psk-identity options.

OPTIONS

      The options below may be given on the command line, but may also be placed in a config file located at $XDG_CONFIG_HOME/mosquitto_sub or $HOME/.config/mosquitto_sub with one
      pair of -option value per line. The values in the config file will be used as defaults and can be overridden by using the command line. The exceptions to this are -t and -T,
      which if given in the config file will not be overridden. Note also that currently some options cannot be negated, e.g.  -S. Config file lines that have a # as the first
      character are treated as comments and not processed any further.
      -A
          Bind the outgoing connection to a local ip address/hostname. Use this argument if you need to restrict network communication to a particular interface.
      -c, --disable-clean-session
          Disable the 'clean session' flag. This means that all of the subscriptions for the client will be maintained after it disconnects, along with subsequent QoS 1 and QoS 2
          messages that arrive. When the client reconnects, it will receive all of the queued messages.
          If using this option, the client id must be set manually with --id
      --cafile
          Define the path to a file containing PEM encoded CA certificates that are trusted. Used to enable SSL communication.
          See also --capath
      --capath
          Define the path to a directory containing PEM encoded CA certificates that are trusted. Used to enable SSL communication.
          For --capath to work correctly, the certificate files must have ".crt" as the file ending and you must run "openssl rehash <path to capath>" each time you add/remove a
          certificate.
          See also --cafile
      --cert
          Define the path to a file containing a PEM encoded certificate for this client, if required by the server.
          See also --key.
      --ciphers
          An openssl compatible list of TLS ciphers to support in the client. See ciphers(1) for more information.
      -C
          Disconnect and exit the program immediately after the given count of messages have been received. This may be useful in shell scripts where on a single status value is
          required, for example.
          Combine with -R to print only the first set of fresh messages (i.e. that does not have the retained flag set), or with -T to filter which topics are processed.
      -d, --debug
          Enable debug messages.
      -D, --property
          Use an MQTT v5 property with this publish. If you use this option, the client will be set to be an MQTT v5 client. This option has two forms:
          -D command identifier value
          -D command identifier name value
          command is the MQTT command/packet identifier and can be one of CONNECT, PUBACK, PUBREC, PUBCOMP, SUBSCRIBE, UNSUBSCRIBE, DISCONNECT, AUTH, or WILL. The properties
          available for each command are listed in the Properties section.
          identifier is the name of the property to add. This is as described in the specification, but with '-' as a word separator. For example: payload-format-indicator. More
          details are in the Properties section.
          value is the value of the property to add, with a data type that is property specific.
          name is only used for the user-property property as the first of the two strings in the string pair. In that case, value is the second of the strings in the pair.
      -E
          If this option is given, mosquitto_sub will exit immediately that all of its subscriptions have been acknowledged by the broker. In conjunction with -c this allows a
          durable client session to be initialised on the broker for future use without requiring any messages to be received.
      -F
          Specify output printing format. This option allows you to choose what information from each message is printed to the screen. See the Output Format section below for full
          details.
          This option overrides the -v option, but does not override the -N option.
      --help
          Display usage information.
      -h, --host
          Specify the host to connect to. Defaults to localhost.
      -i, --id
          The id to use for this client. If not given, a client id will be generated depending on the MQTT version being used. For v3.1.1/v3.1, the client generates a client id in
          the format mosq-XXXXXXXXXXXXXXXXXX, where the X are replaced with random alphanumeric characters. For v5.0, the client sends a zero length client id, and the server will
          generate a client id for the client.
          This option cannot be used at the same time as the --id-prefix argument.
      -I, --id-prefix
          Provide a prefix that the client id will be built from by appending the process id of the client. This is useful where the broker is using the clientid_prefixes option.
          Cannot be used at the same time as the --id argument.
      --insecure
          When using certificate based encryption, this option disables verification of the server hostname in the server certificate. This can be useful when testing initial server
          configurations but makes it possible for a malicious third party to impersonate your server through DNS spoofing, for example. Use this option in testing only. If you need
          to resort to using this option in a production environment, your setup is at fault and there is no point using encryption.
      -k, --keepalive
          The number of seconds between sending PING commands to the broker for the purposes of informing it we are still connected and functioning. Defaults to 60 seconds.
      --key
          Define the path to a file containing a PEM encoded private key for this client, if required by the server.
          See also --cert.
      --keyform
          Specifies the type of private key in use when making TLS connections.. This can be "pem" or "engine". This parameter is useful when a TPM module is being used and the
          private key has been created with it. Defaults to "pem", which means normal private key files are used.
          See also --tls-engine.
      -L, --url
          Specify specify user, password, hostname, port and topic at once as a URL. The URL must be in the form: mqtt(s)://[username[:password]@]host[:port]/topic
          If the scheme is mqtt:// then the port defaults to 1883. If the scheme is mqtts:// then the port defaults to 8883.
      -N
          Do not append an end of line character to the payload when printing. This allows streaming of payload data from multiple messages directly to another application
          unmodified. Only really makes sense when not using -v.
      -p, --port
          Connect to the port specified. If not given, the default of 1883 for plain MQTT or 8883 for MQTT over TLS will be used.
      -P, --pw
          Provide a password to be used for authenticating with the broker. Using this argument without also specifying a username is invalid when using MQTT v3.1 or v3.1.1. See also
          the --username option.
      --proxy
          Specify a SOCKS5 proxy to connect through. "None" and "username" authentication types are supported. The socks-url must be of the form
          socks5h://[username[:password]@]host[:port]. The protocol prefix socks5h means that hostnames are resolved by the proxy. The symbols %25, %3A and %40 are URL decoded into
          %, : and @ respectively, if present in the username or password.
          If username is not given, then no authentication is attempted. If the port is not given, then the default of 1080 is used.
          More SOCKS versions may be available in the future, depending on demand, and will use different protocol prefixes as described in curl(1).
      --psk
          Provide the hexadecimal (no leading 0x) pre-shared-key matching the one used on the broker to use TLS-PSK encryption support.  --psk-identity must also be provided to
          enable TLS-PSK.
      --psk-identity
          The client identity to use with TLS-PSK support. This may be used instead of a username if the broker is configured to do so.
      -q, --qos
          Specify the quality of service desired for the incoming messages, from 0, 1 and 2. Defaults to 0. See mqtt(7) for more information on QoS.
          The QoS is identical for all topics subscribed to in a single instance of mosquitto_sub.
      --quiet
          If this argument is given, no runtime errors will be printed. This excludes any error messages given in case of invalid user input (e.g. using --port without a port).
      -R
          If this argument is given, messages that are received that have the retain bit set will not be printed. Messages with retain set are "stale", in that it is not known when
          they were originally published. When subscribing to a wildcard topic there may be a large number of retained messages. This argument suppresses their display.
      --remove-retained
          If this argument is given, the when mosquitto_sub receives a message with the retained bit set, it will send a message to the broker to clear that retained message. This
          applies to all received messages except those that are filtered out by the -T option. This option still takes effect even if -R is used. See also the --retain-as-published
          and --retained-only options.
          Example 1.  Remove all retained messages on the server, assuming we have access to do so, and then exit:
              mosquitto_sub -t '#' --remove-retained --retained-only
          Example 2.  Remove a whole tree, with the exception of a single topic:
              mosquitto_sub -t 'bbc/#' -T bbc/bbc1 --remove-retained
      --retained-only
          If this argument is given, only messages that are received that have the retain bit set will be printed. Messages with retain set are "stale", in that it is not known when
          they were originally published. With this argument in use, the receipt of the first non-stale message will cause the client to exit. See also the --retain-as-published
          option.
      --retain-as-published
          If this argument is given, the subscriptions will have the "retain as published" option set. This means that the retain flag on an incoming message will be exactly as set
          by the publishing client, rather than indicating whether the message is fresh/stale.
          This option is not valid for MQTT v3.1/v3.1.1 clients.
      -S
          Use SRV lookups to determine which host to connect to. Performs lookups to _mqtt._tcp.<host> when used in conjunction with -h, otherwise uses _mqtt._tcp.<local dns domain>.
      -t, --topic
          The MQTT topic to subscribe to. See mqtt(7) for more information on MQTT topics.
          This option may be repeated to subscribe to multiple topics.
      -T, --filter-out
          Suppress printing of topics that match the filter. This allows subscribing to a wildcard topic and only printing a partial set of the wildcard hierarchy.
          For example, subscribe to the BBC tree, but suppress output from Radio 3:
          ·   mosquitto_sub -t bbc/# -T bbc/radio3
          This option may be repeated to filter out multiple topics or topic trees.
      --tls-alpn
          Provide a protocol to use when connecting to a broker that has multiple protocols available on a single port, e.g. MQTT and WebSockets.
      --tls-engine
          A valid openssl engine id. These can be listed with openssl engine command.
          See also --keyform.
      --tls-engine-kpass-sha1
          SHA1 of the private key password when using an TLS engine. Some TLS engines such as the TPM engine may require the use of a password in order to be accessed. This option
          allows a hex encoded SHA1 hash of the password to the engine directly, instead of the user being prompted for the password.
          See also --tls-engine.
      --tls-version
          Choose which TLS protocol version to use when communicating with the broker. Valid options are tlsv1.3, tlsv1.2 and tlsv1.1. The default value is tlsv1.2. Must match the
          protocol version used by the broker.
      -u, --username
          Provide a username to be used for authenticating with the broker. See also the --pw argument.
      -U, --unsubscribe
          A topic that will be unsubscribed from. This may be used on its own or in conjunction with the --topic option and only makes sense when used in conjunction with
          --clean-session.
          If used with --topic then subscriptions will be processed before unsubscriptions.
          Note that it is only possible to unsubscribe from subscriptions that have previously been made. It is not possible to punch holes in wildcard subscriptions. For example,
          subscribing to sensors/# and then unsubscribing from sensors/+/temperature as shown below will still result in messages matching the sensors/+/temperature being delivered
          to the client.
          ·   mosquitto_sub -t sensors/# -U sensors/+/temperature -v
          Note also that because retained messages are published by the broker on receipt of a SUBSCRIBE command, subscribing and unsubscribing to the same topic may result in
          messages being received at the client.
          This option may be repeated to unsubscribe from multiple topics.
      -v, --verbose
          Print received messages verbosely. With this argument, messages will be printed as "topic payload". When this argument is not given, the messages are printed as "payload".
      -V, --protocol-version
          Specify which version of the MQTT protocol should be used when connecting to the remote broker. Can be 5, 311, 31, or the more verbose mqttv5, mqttv311, or mqttv31.
          Defaults to 311.
      -W
          Provide a timeout as an integer number of seconds. mosquitto_sub will stop processing messages and disconnect after this number of seconds has passed. The timeout starts
          just after the client has connected to the broker.
      --will-payload
          Specify a message that will be stored by the broker and sent out if this client disconnects unexpectedly. This must be used in conjunction with --will-topic.
      --will-qos
          The QoS to use for the Will. Defaults to 0. This must be used in conjunction with --will-topic.
      --will-retain
          If given, if the client disconnects unexpectedly the message sent out will be treated as a retained message. This must be used in conjunction with --will-topic.
      --will-topic
          The topic on which to send a Will, in the event that the client disconnects unexpectedly.

OUTPUT FORMAT

      There are three ways of formatting the output from mosquitto_sub. In all cases a new-line character is appended for each message received unless the -N argument is passed to
      mosquitto_sub.
      Payload-only is the default output format and will print the payload exactly as it is received.
      Verbose mode is activated with -v and prints the message topic and the payload, separated by a space.
      The final option is formatted output, which allows the user to define a custom output format. The behaviour is controlled with the -F format-string option. The format string is
      a free text string where interpreted sequences are replaced by different parameters. The available interpreted sequences are described below.
      Three characters are used to start an interpreted sequence: %, @ and \. Sequences starting with % are either parameters related to the MQTT message being printed, or are helper
      sequences to avoid the need to type long date format strings for example. Sequences starting with @ are passed to the strftime(3) function (with the @ replaced with a % - note
      that only the character immediately after the @ is passed to strftime). This allows the construction of a wide variety of time based outputs. The output options for strftime
      vary from platform to platform, so please check what is available for your platform. mosquitto_sub does provide one extension to strftime which is @N, which can be used to
      obtain the number of nanoseconds passed in the current second. The resolution of this option varies depending on the platform. The final sequence character is \, which is used
      to input some characters that would otherwise be difficult to enter.
  MQTT related parameters
      ·   %% a literal %.
      ·   %l the length of the payload in bytes.
      ·   %m the message id (only relevant for messages with QoS>0).
      ·   %p the payload raw bytes (may produce non-printable characters depending on the payload).
      ·   %q the message QoS.
      ·   %r the retained flag for the message.
      ·   %t the message topic.
      ·   %x the payload with each byte as a hexadecimal number (lower case).
      ·   %X the payload with each byte as a hexadecimal number (upper case).
  Helpers
      ·   %I ISO-8601 format date and time, e.g. 2016-08-10T09:47:38+0100
      ·   %j JSON output of message parameters and timestamp, with a quoted and escaped payload. For example {"tst":1470825369,"topic":"greeting","qos":0,"retain":0,"payload":"hello
          world"}
      ·   %J JSON output of message parameters and timestamp, with a non-quoted and non-escaped payload - this means the payload must itself be valid JSON. For example:
          {"tst":1470825369,"topic":"foo","qos":0,"retain":0,"payload":{"temperature":27.0,"humidity":57}}.
      ·   %I ISO-8601 format date and time, e.g. 2016-08-10T09:47:38+0100
      ·   %U Unix timestamp with nanoseconds, e.g. 1470818943.786368637
  Time related parameters
      ·   @@ a literal @.
      ·   @X pass the character represented by X to the strftime function as %X. The options supported are platform dependent.
      ·   @N the number of nanoseconds that have passed in the current second, with varying timing resolution depending on platform.
  Escape characters
      ·   \\ a literal \.
      ·   \0 a null character. Can be used to separate different parameters that may contain spaces (e.g. topic, payload) so that processing with tools such as xargs(1) is easier.
      ·   \a alert/bell.
      ·   \e the escape sequence, which can be used with ANSI colour codes to provide coloured output for example.
      ·   \n end of line.
      ·   \r carriage return.
      ·   \t horizontal tab.
      ·   \v vertical tab.

WILLS

      mosquitto_sub can register a message with the broker that will be sent out if it disconnects unexpectedly. See mqtt(7) for more information.
      The minimum requirement for this is to use --will-topic to specify which topic the will should be sent out on. This will result in a non-retained, zero length message with QoS
      0.
      Use the --will-retain, --will-payload and --will-qos arguments to modify the other will parameters.

PROPERTIES

      The -D / --property option allows adding properties to different stages of the mosquitto_sub run. The properties supported for each command are as follows:
  Connect
      ·   authentication-data (binary data - note treated as a string in mosquitto_sub)
      ·   authentication-method (UTF-8 string pair)
      ·   maximum-packet-size (32-bit unsigned integer)
      ·   receive-maximum (16-bit unsigned integer)
      ·   request-problem-information (8-bit unsigned integer)
      ·   request-response-information (8-bit unsigned integer)
      ·   session-expiry-interval (32-bit unsigned integer)
      ·   topic-alias-maximum (16-bit unsigned integer)
      ·   user-property (UTF-8 string pair)
  Subscribe
      ·   user-property (UTF-8 string pair)
  Unsubscribe
      ·   user-property (UTF-8 string pair)
  Disconnect
      ·   session-expiry-interval (32-bit unsigned integer)
      ·   user-property (UTF-8 string pair)
  Will properties
      ·   content-type (UTF-8 string)
      ·   correlation-data (binary data - note treated as a string in mosquitto_sub)
      ·   message-expiry-interval (32-bit unsigned integer)
      ·   payload-format-indicator (8-bit unsigned integer)
      ·   response-topic (UTF-8 string)
      ·   user-property (UTF-8 string pair)
      ·   will-delay-interval (32-bit unsigned integer)

EXAMPLES

      Note that these really are examples - the subscriptions will work if you run them as shown, but there must be something publishing messages on those topics for you to receive
      anything.
      Subscribe to temperature information on localhost with QoS 1:
      ·   mosquitto_sub -t sensors/temperature -q 1
      Subscribe to hard drive temperature updates on multiple machines/hard drives. This expects each machine to be publishing its hard drive temperature to
      sensors/machines/HOSTNAME/temperature/HD_NAME.
      ·   mosquitto_sub -t sensors/machines/+/temperature/+
      Subscribe to all broker status messages:
      ·   mosquitto_sub -v -t \$SYS/#
      Specify the output format as "ISO-8601 date : topic : payload in hex"
      ·   mosquitto_sub -F '@Y-@m-@dT@H:@M:@S@z : %t : %x' -t '#'
      Specify the output format as "seconds since epoch.nanoseconds : retained flag : qos : mid : payload length"
      ·   mosquitto_sub -F '%@s.@N : %r : %q : %m : %l' -q 2 -t '#'
      Topic and payload output, but with colour where supported.
      ·   mosquitto_sub -F '\e[92m%t \e[96m%p\e[0m' -q 2 -t '#'

FILES

      $XDG_CONFIG_HOME/mosquitto_sub, $HOME/.config/mosquitto_sub
          Configuration file for default options.

BUGS

      mosquitto bug information can be found at https://github.com/eclipse/mosquitto/issues

SEE ALSO

      mqtt(7), mosquitto_pub(1), mosquitto_rr(1), mosquitto(8), libmosquitto(3), mosquitto-tls(7)

AUTHOR

      Roger Light <roger@atchoo.org>

mosquitto_rr

MOSQUITTO_RR(1)

NAME

      mosquitto_rr - an MQTT version 5/3.1.1 client for request/response messaging

SYNOPSIS

      mosquitto_rr {[-h hostname] [-p port-number] [-u username] [-P password] -t message-topic...  | -L URL [-t message-topic...]  | [-e response-topic]} {-f file | -m message | -n
                   | -s} [-A bind-address] [-c] [-d] [-D command identifier value] [-i client-id] [-I client-id-prefix] [-k keepalive-time] [-N] [-q message-QoS] [-R] [-S] [-v]
                   [-V protocol-version] [-W message-processing-timeout] [--proxy socks-url] [--quiet] [--will-topic topic [--will-payload payload] [--will-qos qos] [--will-retain]]
                   [[{--cafile file | --capath dir} [--cert file] [--key file] [--ciphers ciphers] [--tls-version version] [--tls-alpn protocol] [--tls-engine engine] [--keyform {pem | engine}] [--tls-engine-kpass-sha1 kpass-sha1] [--insecure]]
                   | [--psk hex-key --psk-identity identity [--ciphers ciphers] [--tls-version version]]]
      mosquitto_rr [--help]

DESCRIPTION

      mosquitto_rr is an MQTT version 5/3.1.1 client that can be used to publish a request message and wait for a response. When using MQTT v5, which is the default, mosquitto_rr
      will use the Request-Response feature.

ENCRYPTED CONNECTIONS

      mosquitto_rr supports TLS encrypted connections. It is strongly recommended that you use an encrypted connection for anything more than the most basic setup.
      To enable TLS connections when using x509 certificates, one of either --cafile or --capath must be provided as an option.
      To enable TLS connections when using TLS-PSK, you must use the --psk and the --psk-identity options.

OPTIONS

      The options below may be given on the command line, but may also be placed in a config file located at $XDG_CONFIG_HOME/mosquitto_rr or $HOME/.config/mosquitto_rr with one pair
      of -option value per line. The values in the config file will be used as defaults and can be overridden by using the command line. The exceptions to this is -t, which if given
      in the config file will not be overridden. Note also that currently some options cannot be negated, e.g.  -S. Config file lines that have a # as the first character are treated
      as comments and not processed any further.
      -A
          Bind the outgoing connection to a local ip address/hostname. Use this argument if you need to restrict network communication to a particular interface.
      -c, --disable-clean-session
          Disable the 'clean session' flag. This means that all of the subscriptions for the client will be maintained after it disconnects, along with subsequent QoS 1 and QoS 2
          messages that arrive. When the client reconnects, it will receive all of the queued messages.
          If using this option, the client id must be set manually with --id
      --cafile
          Define the path to a file containing PEM encoded CA certificates that are trusted. Used to enable SSL communication.
          See also --capath
      --capath
          Define the path to a directory containing PEM encoded CA certificates that are trusted. Used to enable SSL communication.
          For --capath to work correctly, the certificate files must have ".crt" as the file ending and you must run "openssl rehash <path to capath>" each time you add/remove a
          certificate.
          See also --cafile
      --cert
          Define the path to a file containing a PEM encoded certificate for this client, if required by the server.
          See also --key.
      --ciphers
          An openssl compatible list of TLS ciphers to support in the client. See ciphers(1) for more information.
      -d, --debug
          Enable debug messages.
      -D, --property
          Use an MQTT v5 property with this publish. If you use this option, the client will be set to be an MQTT v5 client. This option has two forms:
          -D command identifier value
          -D command identifier name value
          command is the MQTT command/packet identifier and can be one of CONNECT, PUBACK, PUBREC, PUBCOMP, SUBSCRIBE, UNSUBSCRIBE, DISCONNECT, AUTH, or WILL. The properties
          available for each command are listed in the Properties section.
          identifier is the name of the property to add. This is as described in the specification, but with '-' as a word separator. For example: payload-format-indicator. More
          details are in the Properties section.
          value is the value of the property to add, with a data type that is property specific.
          name is only used for the user-property property as the first of the two strings in the string pair. In that case, value is the second of the strings in the pair.
      -f, --file
          Send the contents of a file as the request message.
      -F
          Specify output printing format. This option allows you to choose what information from each message is printed to the screen. See the Output Format section below for full
          details.
          This option overrides the -v option, but does not override the -N option.
      --help
          Display usage information.
      -h, --host
          Specify the host to connect to. Defaults to localhost.
      -i, --id
          The id to use for this client. If not given, a client id will be generated depending on the MQTT version being used. For v3.1.1/v3.1, the client generates a client id in
          the format mosq-XXXXXXXXXXXXXXXXXX, where the X are replaced with random alphanumeric characters. For v5.0, the client sends a zero length client id, and the server will
          generate a client id for the client.
          This option cannot be used at the same time as the --id-prefix argument.
      -I, --id-prefix
          Provide a prefix that the client id will be built from by appending the process id of the client. This is useful where the broker is using the clientid_prefixes option.
          Cannot be used at the same time as the --id argument.
      --insecure
          When using certificate based encryption, this option disables verification of the server hostname in the server certificate. This can be useful when testing initial server
          configurations but makes it possible for a malicious third party to impersonate your server through DNS spoofing, for example. Use this option in testing only. If you need
          to resort to using this option in a production environment, your setup is at fault and there is no point using encryption.
      -k, --keepalive
          The number of seconds between sending PING commands to the broker for the purposes of informing it we are still connected and functioning. Defaults to 60 seconds.
      --key
          Define the path to a file containing a PEM encoded private key for this client, if required by the server.
          See also --cert.
      --keyform
          Specifies the type of private key in use when making TLS connections.. This can be "pem" or "engine". This parameter is useful when a TPM module is being used and the
          private key has been created with it. Defaults to "pem", which means normal private key files are used.
          See also --tls-engine.
      -L, --url
          Specify specify user, password, hostname, port and topic at once as a URL. The URL must be in the form: mqtt(s)://[username[:password]@]host[:port]/topic
          If the scheme is mqtt:// then the port defaults to 1883. If the scheme is mqtts:// then the port defaults to 8883.
      -m, --message
          Send a single request message from the command line.
      -N
          Do not append an end of line character to the payload when printing. This allows streaming of payload data from multiple messages directly to another application
          unmodified. Only really makes sense when not using -v.
      -n, --null-message
          Send a null (zero length) request message.
      -p, --port
          Connect to the port specified. If not given, the default of 1883 for plain MQTT or 8883 for MQTT over TLS will be used.
      -P, --pw
          Provide a password to be used for authenticating with the broker. Using this argument without also specifying a username is invalid when using MQTT v3.1 or v3.1.1. See also
          the --username option.
      --proxy
          Specify a SOCKS5 proxy to connect through. "None" and "username" authentication types are supported. The socks-url must be of the form
          socks5h://[username[:password]@]host[:port]. The protocol prefix socks5h means that hostnames are resolved by the proxy. The symbols %25, %3A and %40 are URL decoded into
          %, : and @ respectively, if present in the username or password.
          If username is not given, then no authentication is attempted. If the port is not given, then the default of 1080 is used.
          More SOCKS versions may be available in the future, depending on demand, and will use different protocol prefixes as described in curl(1).
      --psk
          Provide the hexadecimal (no leading 0x) pre-shared-key matching the one used on the broker to use TLS-PSK encryption support.  --psk-identity must also be provided to
          enable TLS-PSK.
      --psk-identity
          The client identity to use with TLS-PSK support. This may be used instead of a username if the broker is configured to do so.
      -q, --qos
          Specify the quality of service desired for the incoming messages, from 0, 1 and 2. Defaults to 0. See mqtt(7) for more information on QoS.
          The QoS is identical for all topics subscribed to in a single instance of mosquitto_rr.
      --quiet
          If this argument is given, no runtime errors will be printed. This excludes any error messages given in case of invalid user input (e.g. using --port without a port).
      -R
          If this argument is given, messages that are received that have the retain bit set will not be printed. Messages with retain set are "stale", in that it is not known when
          they were originally published. When subscribing to a wildcard topic there may be a large number of retained messages. This argument suppresses their display.
      -S
          Use SRV lookups to determine which host to connect to. Performs lookups to _mqtt._tcp.<host> when used in conjunction with -h, otherwise uses _mqtt._tcp.<local dns domain>.
      -s, --stdin-file
          Send a request message read from stdin, sending the entire content as a single message.
      -t, --topic
          The MQTT topic to subscribe to, where responses will be waited for. See mqtt(7) for more information on MQTT topics.
          This option may be repeated to subscribe to multiple topics.
      --tls-alpn
          Provide a protocol to use when connecting to a broker that has multiple protocols available on a single port, e.g. MQTT and WebSockets.
      --tls-engine
          A valid openssl engine id. These can be listed with openssl engine command.
          See also --keyform.
      --tls-engine-kpass-sha1
          SHA1 of the private key password when using an TLS engine. Some TLS engines such as the TPM engine may require the use of a password in order to be accessed. This option
          allows a hex encoded SHA1 hash of the password to the engine directly, instead of the user being prompted for the password.
          See also --tls-engine.
      --tls-version
          Choose which TLS protocol version to use when communicating with the broker. Valid options are tlsv1.3, tlsv1.2 and tlsv1.1. The default value is tlsv1.2. Must match the
          protocol version used by the broker.
      -u, --username
          Provide a username to be used for authenticating with the broker. See also the --pw argument.
      -v, --verbose
          Print received messages verbosely. With this argument, messages will be printed as "topic payload". When this argument is not given, the messages are printed as "payload".
      -V, --protocol-version
          Specify which version of the MQTT protocol should be used when connecting to the rmeote broker. Can be 5, 311, 31, or the more verbose mqttv5, mqttv311, or mqttv31.
          Defaults to 311.
      --will-payload
          Specify a message that will be stored by the broker and sent out if this client disconnects unexpectedly. This must be used in conjunction with --will-topic.
      --will-qos
          The QoS to use for the Will. Defaults to 0. This must be used in conjunction with --will-topic.
      --will-retain
          If given, if the client disconnects unexpectedly the message sent out will be treated as a retained message. This must be used in conjunction with --will-topic.
      --will-topic
          The topic on which to send a Will, in the event that the client disconnects unexpectedly.

OUTPUT FORMAT

      There are three ways of formatting the output from mosquitto_rr. In all cases a new-line character is appended for each message received unless the -N argument is passed to
      mosquitto_rr.
      Payload-only is the default output format and will print the payload exactly as it is received.
      Verbose mode is activated with -v and prints the message topic and the payload, separated by a space.
      The final option is formatted output, which allows the user to define a custom output format. The behaviour is controlled with the -F format-string option. The format string is
      a free text string where interpreted sequences are replaced by different parameters. The available interpreted sequences are described below.
      Three characters are used to start an interpreted sequence: %, @ and \. Sequences starting with % are either parameters related to the MQTT message being printed, or are helper
      sequences to avoid the need to type long date format strings for example. Sequences starting with @ are passed to the strftime(3) function (with the @ replaced with a % - note
      that only the character immediately after the @ is passed to strftime). This allows the construction of a wide variety of time based outputs. The output options for strftime
      vary from platform to platform, so please check what is available for your platform. mosquitto_rr does provide one extension to strftime which is @N, which can be used to
      obtain the number of nanoseconds passed in the current second. The resolution of this option varies depending on the platform. The final sequence character is \, which is used
      to input some characters that would otherwise be difficult to enter.
  MQTT related parameters
      ·   %% a literal %.
      ·   %l the length of the payload in bytes.
      ·   %m the message id (only relevant for messages with QoS>0).
      ·   %p the payload raw bytes (may produce non-printable characters depending on the payload).
      ·   %q the message QoS.
      ·   %r the retained flag for the message.
      ·   %t the message topic.
      ·   %x the payload with each byte as a hexadecimal number (lower case).
      ·   %X the payload with each byte as a hexadecimal number (upper case).
  Helpers
      ·   %I ISO-8601 format date and time, e.g. 2016-08-10T09:47:38+0100
      ·   %j JSON output of message parameters and timestamp, with a quoted and escaped payload. For example {"tst":1470825369,"topic":"greeting","qos":0,"retain":0,"payload":"hello
          world"}
      ·   %J JSON output of message parameters and timestamp, with a non-quoted and non-escaped payload - this means the payload must itself be valid JSON. For example:
          {"tst":1470825369,"topic":"foo","qos":0,"retain":0,"payload":{"temperature":27.0,"humidity":57}}.
      ·   %I ISO-8601 format date and time, e.g. 2016-08-10T09:47:38+0100
      ·   %U Unix timestamp with nanoseconds, e.g. 1470818943.786368637
  Time related parameters
      ·   @@ a literal @.
      ·   @X pass the character represented by X to the strftime function as %X. The options supported are platform dependent.
      ·   @N the number of nanoseconds that have passed in the current second, with varying timing resolution depending on platform.
  Escape characters
      ·   \\ a literal \.
      ·   \0 a null character. Can be used to separate different parameters that may contain spaces (e.g. topic, payload) so that processing with tools such as xargs(1) is easier.
      ·   \a alert/bell.
      ·   \e the escape sequence, which can be used with ANSI colour codes to provide coloured output for example.
      ·   \n end of line.
      ·   \r carriage return.
      ·   \t horizontal tab.
      ·   \v vertical tab.

WILLS

      mosquitto_rr can register a message with the broker that will be sent out if it disconnects unexpectedly. See mqtt(7) for more information.
      The minimum requirement for this is to use --will-topic to specify which topic the will should be sent out on. This will result in a non-retained, zero length message with QoS
      0.
      Use the --will-retain, --will-payload and --will-qos arguments to modify the other will parameters.

PROPERTIES

      The -D / --property option allows adding properties to different stages of the mosquitto_rr run. The properties supported for each command are as follows:
  Connect
      ·   authentication-data (binary data - note treated as a string in mosquitto_rr)
      ·   authentication-method (UTF-8 string pair)
      ·   maximum-packet-size (32-bit unsigned integer)
      ·   receive-maximum (16-bit unsigned integer)
      ·   request-problem-information (8-bit unsigned integer)
      ·   request-response-information (8-bit unsigned integer)
      ·   session-expiry-interval (32-bit unsigned integer)
      ·   topic-alias-maximum (16-bit unsigned integer)
      ·   user-property (UTF-8 string pair)
  Publish
      ·   content-type (UTF-8 string)
      ·   correlation-data (binary data - note treated as a string in mosquitto_rr)
      ·   message-expiry-interval (32-bit unsigned integer)
      ·   payload-format-indicator (8-bit unsigned integer)
      ·   response-topic (UTF-8 string)
      ·   topic-alias (16-bit unsigned integer)
      ·   user-property (UTF-8 string pair)
  Subscribe
      ·   user-property (UTF-8 string pair)
  Unsubscribe
      ·   user-property (UTF-8 string pair)
  Disconnect
      ·   session-expiry-interval (32-bit unsigned integer)
      ·   user-property (UTF-8 string pair)
  Will properties
      ·   content-type (UTF-8 string)
      ·   correlation-data (binary data - note treated as a string in mosquitto_pub)
      ·   message-expiry-interval (32-bit unsigned integer)
      ·   payload-format-indicator (8-bit unsigned integer)
      ·   response-topic (UTF-8 string)
      ·   user-property (UTF-8 string pair)
      ·   will-delay-interval (32-bit unsigned integer)

FILES

      $XDG_CONFIG_HOME/mosquitto_rr, $HOME/.config/mosquitto_rr
          Configuration file for default options.

BUGS

      mosquitto bug information can be found at https://github.com/eclipse/mosquitto/issues

SEE ALSO

      mqtt(7), mosquitto_pub(1), mosquitto_sub(1), mosquitto(8), libmosquitto(3), mosquitto-tls(7)

AUTHOR

      Roger Light <roger@atchoo.org>

mosquitto-tls

mosquitto-tls ist scheinbar kein eigenstaendiges Programm. Ich konnte es keinem OpenSuSE-Repository finden. Es gibt aber eine ManPage.

man mosquitto-tlls
 1 MOSQUITTO-TLS(7)     Conventions and miscellaneous                                                                   
 2 
 3 NAME
 4        mosquitto-tls - Configure SSL/TLS support for Mosquitto
 5 
 6 DESCRIPTION
 7        mosquitto provides SSL support for encrypted network connections and authentication. This manual describes how to create the files needed.
 8 
 9            Note
10            It is important to use different certificate subject parameters for your CA, server and clients. If the certificates appear identical, even though generated separately, the
11            broker/client will not be able to distinguish between them and you will experience difficult to diagnose errors.
12 
13 GENERATING CERTIFICATES
14        The sections below give the openssl commands that can be used to generate certificates, but without any context. The asciicast at https://asciinema.org/a/201826 gives a full run through of
15        how to use those commands.
16 
17 CERTIFICATE AUTHORITY
18        Generate a certificate authority certificate and key.
19 
20        ·   openssl req -new -x509 -days <duration> -extensions v3_ca -keyout ca.key -out ca.crt
21 
22 SERVER
23        Generate a server key.
24 
25        ·   openssl genrsa -des3 -out server.key 2048
26 
27        Generate a server key without encryption.
28 
29        ·   openssl genrsa -out server.key 2048
30 
31        Generate a certificate signing request to send to the CA.
32 
33        ·   openssl req -out server.csr -key server.key -new
34 
35            Note
36            When prompted for the CN (Common Name), please enter either your server (or broker) hostname or domain name.
37 
38        Send the CSR to the CA, or sign it with your CA key:
39 
40        ·   openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days <duration>
41 
42 CLIENT
43        Generate a client key.
44 
45        ·   openssl genrsa -des3 -out client.key 2048
46 
47        Generate a certificate signing request to send to the CA.
48 
49        ·   openssl req -out client.csr -key client.key -new
50 
51        Send the CSR to the CA, or sign it with your CA key:
52 
53        ·   openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days <duration>
54 
55 SEE ALSO
56        mosquitto(8), mosquitto-conf(5)
57 
58 AUTHOR
59        Roger Light <roger@atchoo.org>

Ein Anwendungsbeschreibung ist hier zu finden.

mosquitto_ctrl

TODO

mosquitto_password

TODO

Topic Level

Es wird nicht empfohlen vor dem ersten Topic ein Slash (Leading Slash) voranzustellen. https://www.hivemq.com/blog/mqtt-essentials-part-5-mqtt-topics-best-practices/

  • kein Slash zu Beginn. Ist zwar erlaubt, aber besser nicht nutzen.
  • mindestens 1 Buchstabe lang
  • Leerzeichen sind erlaubt, sollen aber vermieden werden
  • Groß- und Kleinschreibung wird beachtet

Wildcards:

  • + ersetzt einen Level
  • # ersetzt alle folgenden Level, somit steht das Hash immer am Ende

MQTT Mitschnitte

Connect/Disconnect

Die fehlenden Frames waren andere nicht zur Kommunikation gehörende Pakete.

3 mal Connect/Disconnect eines Clients (192.168.2.49)
7 12.042582120 192.168.2.49 192.168.2.1 TCP 66 55338 → 1883 [SYN] Seq=0 Win=64240 Len=0 MSS=1460 WS=256 SACK_PERM=1
8 12.042655080 192.168.2.1 192.168.2.49 TCP 66 1883 → 55338 [SYN, ACK] Seq=0 Ack=1 Win=64240 Len=0 MSS=1460 SACK_PERM=1 WS=128
9 12.042925688 192.168.2.49 192.168.2.1 TCP 60 55338 → 1883 [ACK] Seq=1 Ack=1 Win=2102272 Len=0
10 12.043312742 192.168.2.49 192.168.2.1 MQTT 104 Connect Command [PSH, ACK] Seq=1 Ack=1 
11 12.043341219 192.168.2.1 192.168.2.49 TCP 54 1883 → 55338 [ACK] Seq=1 Ack=51 Win=64256 Len=0
12 12.043406086 192.168.2.1 192.168.2.49 MQTT 58 Connect Ack  [PSH, ACK] Seq=1 Ack=51 
13 12.048162031 192.168.2.49 192.168.2.1 MQTT 66 Subscribe Request [PSH, ACK] Seq=51 Ack=5 (id=1) [homie]
14 12.048187408 192.168.2.1 192.168.2.49 TCP 54 1883 → 55338 [ACK] Seq=5 Ack=63 Win=64256 Len=0
15 12.048266601 192.168.2.1 192.168.2.49 MQTT 59 Subscribe Ack [PSH, ACK] (id=1)
16 12.088233552 192.168.2.49 192.168.2.1 TCP 60 55338 → 1883 [ACK] Seq=63 Ack=10 Win=2102272 Len=0
17 17.992117496 192.168.2.49 192.168.2.1 MQTT 60 Disconnect Req [PSH, ACK]  Seq=63 Ack=10 
18 17.992157890 192.168.2.1 192.168.2.49 TCP 54 1883 → 55338 [ACK] Seq=10 Ack=65 Win=64256 Len=0
19 17.992173280 192.168.2.49 192.168.2.1 MQTT 61 Unsubscribe Request  [PSH, ACK] Seq=65 Ack=10 (id=2)
20 17.992181887 192.168.2.1 192.168.2.49 TCP 54 1883 → 55338 [ACK] Seq=10 Ack=72 Win=64256 Len=0
21 17.992228446 192.168.2.1 192.168.2.49 TCP 54 1883 → 55338 [RST, ACK] Seq=10 Ack=72 Win=64256 Len=0
22 18.916403941 192.168.2.49 192.168.2.1 TCP 60 55191 → 1883 [RST, ACK] Seq=2 Ack=1 Win=0 Len=0
================ 
23 28.228693903 192.168.2.49 192.168.2.1 TCP 66 55340 → 1883 [SYN] Seq=0 Win=64240 Len=0 MSS=1460 WS=256 SACK_PERM=1
24 28.228758802 192.168.2.1 192.168.2.49 TCP 66 1883 → 55340 [SYN, ACK] Seq=0 Ack=1 Win=64240 Len=0 MSS=1460 SACK_PERM=1 WS=128
25 28.229003757 192.168.2.49 192.168.2.1 TCP 60 55340 → 1883 [ACK] Seq=1 Ack=1 Win=2102272 Len=0
26 28.229490136 192.168.2.49 192.168.2.1 MQTT 104 Connect Command
27 28.229519908 192.168.2.1 192.168.2.49 TCP 54 1883 → 55340 [ACK] Seq=1 Ack=51 Win=64256 Len=0
28 28.229637725 192.168.2.1 192.168.2.49 MQTT 58 Connect Ack
29 28.231446525 192.168.2.49 192.168.2.1 MQTT 66 Subscribe Request (id=1) [homie]
30 28.231476361 192.168.2.1 192.168.2.49 TCP 54 1883 → 55340 [ACK] Seq=5 Ack=63 Win=64256 Len=0
31 28.231573403 192.168.2.1 192.168.2.49 MQTT 59 Subscribe Ack (id=1)
32 28.273477925 192.168.2.49 192.168.2.1 TCP 60 55340 → 1883 [ACK] Seq=63 Ack=10 Win=2102272 Len=0
33 35.418744664 192.168.2.49 192.168.2.1 MQTT 60 Disconnect Req
34 35.418795198 192.168.2.1 192.168.2.49 TCP 54 1883 → 55340 [ACK] Seq=10 Ack=65 Win=64256 Len=0
35 35.418910606 192.168.2.1 192.168.2.49 TCP 54 1883 → 55340 [FIN, ACK] Seq=10 Ack=65 Win=64256 Len=0
36 35.419316214 192.168.2.49 192.168.2.1 MQTT 61 Unsubscribe Request (id=2)
37 35.419350837 192.168.2.1 192.168.2.49 TCP 54 1883 → 55340 [RST] Seq=10 Win=0 Len=0
38 35.420229171 192.168.2.49 192.168.2.1 TCP 60 55340 → 1883 [ACK] Seq=72 Ack=11 Win=2102272 Len=0
39 35.420259593 192.168.2.1 192.168.2.49 TCP 54 1883 → 55340 [RST] Seq=11 Win=0 Len=0
================ 
40 43.441601362 192.168.2.49 192.168.2.1 TCP 66 55344 → 1883 [SYN] Seq=0 Win=64240 Len=0 MSS=1460 WS=256 SACK_PERM=1
41 43.441665532 192.168.2.1 192.168.2.49 TCP 66 1883 → 55344 [SYN, ACK] Seq=0 Ack=1 Win=64240 Len=0 MSS=1460 SACK_PERM=1 WS=128
42 43.441988766 192.168.2.49 192.168.2.1 TCP 60 55344 → 1883 [ACK] Seq=1 Ack=1 Win=2102272 Len=0
43 43.442522211 192.168.2.49 192.168.2.1 MQTT 104 Connect Command
44 43.442554807 192.168.2.1 192.168.2.49 TCP 54 1883 → 55344 [ACK] Seq=1 Ack=51 Win=64256 Len=0
45 43.442640108 192.168.2.1 192.168.2.49 MQTT 58 Connect Ack
46 43.443729866 192.168.2.49 192.168.2.1 MQTT 66 Subscribe Request (id=1) [homie]
47 43.443755286 192.168.2.1 192.168.2.49 TCP 54 1883 → 55344 [ACK] Seq=5 Ack=63 Win=64256 Len=0
48 43.443847297 192.168.2.1 192.168.2.49 MQTT 59 Subscribe Ack (id=1)
49 43.485302146 192.168.2.49 192.168.2.1 TCP 60 55344 → 1883 [ACK] Seq=63 Ack=10 Win=2102272 Len=0
50 53.655694260 192.168.2.49 192.168.2.1 MQTT 61 Unsubscribe Request (id=2)
51 53.655741788 192.168.2.1 192.168.2.49 TCP 54 1883 → 55344 [ACK] Seq=10 Ack=70 Win=64256 Len=0
52 53.655802046 192.168.2.1 192.168.2.49 MQTT 58 Unsubscribe Ack (id=2)
53 53.662489828 192.168.2.49 192.168.2.1 MQTT 60 Disconnect Req
54 53.662518762 192.168.2.1 192.168.2.49 TCP 54 1883 → 55344 [ACK] Seq=14 Ack=72 Win=64256 Len=0
55 53.662591294 192.168.2.1 192.168.2.49 TCP 54 1883 → 55344 [FIN, ACK] Seq=14 Ack=72 Win=64256 Len=0
56 53.662779123 192.168.2.49 192.168.2.1 TCP 60 55344 → 1883 [ACK] Seq=72 Ack=15 Win=2102272 Len=0
57 53.664641301 192.168.2.49 192.168.2.1 TCP 60 55344 → 1883 [RST, ACK] Seq=72 Ack=15 Win=0 Len=0

Was erstaunt ist die Unterschiedlichkeit des Ablaufs beim Unsubcribe, bzw. Disconnect. Aber der Reihe nach. Auf dem Client habe ich 3 mal hintereinander Subscribe und dann Disconnect gedrückt. Der Dummy-Topic war 'homie'. Die ersten 3 TCP-Pakete sind der Verbindungsaufbau.

SYN (S0A0) -> SYNACK (S0A1) -> ACK (S1A1)

Ab Frame 10 erfolgt der MQTT connect. Die Flags PUSH und ACK sind gesetzt.

0000   1c c1 de 32 98 c9 5c 85 7e 43 11 b4 08 00 45 00   ...2..\.~C....E.
0010   00 5a 8c cf 40 00 80 06 e8 4b c0 a8 02 31 c0 a8   .Z..@....K...1..
0020   02 01 d8 2a 07 5b c3 e2 91 13 91 63 d1 ad 50 18   ...*.[.....c..P.
0030   20 14 91 ff 00 00 10 30 00 04 4d 51 54 54 04 02    ......0..MQTT..
0040   00 3c 00 24 34 30 61 61 66 38 66 38 2d 32 39 39   .<.$40aaf8f8-299
0050   66 2d 34 33 32 31 2d 39 36 65 63 2d 34 34 39 36   f-4321-96ec-4496
0060   62 66 66 39 34 35 64 30                           bff945d0

Ab Position 0036 steht der MQTT Payload:

MQ Telemetry Transport Protocol, Connect Command
   Header Flags: 0x10, Message Type: Connect Command
   Msg Len: 48
   Protocol Name Length: 4
   Protocol Name: MQTT
   Version: MQTT v3.1.1 (4)
   Connect Flags: 0x02, QoS Level: At most once delivery (Fire and Forget), Clean Session Flag
   Keep Alive: 60
   Client ID Length: 36
   Client ID: 40aaf8f8-299f-4321-96ec-4496bff945d0

Mit Frame 11 und 12 folgenden die Quittungen der Schicht 3 und 4. In Frame 12 sind die Flags PUSH und ACK gesetzt. Der Inhalt ist 20 02 00 00.

MQ Telemetry Transport Protocol, Connect Ack
   Header Flags: 0x20, Message Type: Connect Ack
   Msg Len: 2
   Acknowledge Flags: 0x00
   Return Code: Connection Accepted (0)

Ab Frame 13 erfolgt die Subscription des Topic 'homie'.

0000   1c c1 de 32 98 c9 5c 85 7e 43 11 b4 08 00 45 00   ...2..\.~C....E.
0010   00 34 8c d0 40 00 80 06 e8 70 c0 a8 02 31 c0 a8   .4..@....p...1..
0020   02 01 d8 2a 07 5b c3 e2 91 45 91 63 d1 b1 50 18   ...*.[...E.c..P.
0030   20 14 b5 7a 00 00 82 0a 00 01 00 05 68 6f 6d 69    ..z........homi
0040   65 02                                             e.
MQ Telemetry Transport Protocol, Subscribe Request
   Header Flags: 0x82, Message Type: Subscribe Request
   Msg Len: 10
   Message Identifier: 1
   Topic Length: 5
   Topic: homie
   Requested QoS: Exactly once delivery (Assured Delivery) (2)

Mit Frame 14 und 15 folgenden die Quittungen der Schicht 3 und 4. Und mit Frame 16 folgt die TCP-Quittung des Clients.

Ab Frame 17 folgt der Disconnect. Interessant ist jetzt die Reihenfolge. Im Client wurde zwar der Disconnect auslgelöst, aber man hätte erwartet, dass der Client korrekterweise erst ein Unsubscribe verschickt. Stattdessen sendet er erst ein Disconnect und dann ein Unsubscribe! Beide werden jeweils mit einem TCP-ACK quittiert (18 und 20). Dann bricht der Server die Verbindung mit einem RSTACK ab. Danach bricht auch der Client mit einem RSTACK ab.

Ab Frame 23, ebenso ab Frame 40, beginnt die erneute Kontaktaufnahme, jeweils durch Starten der Subscription. Was aber auffällt:

  • Der Disconnect Request wird beim zweiten Mal zusätzlich mit einem FINACK quittiert.
  • Der Unsubscribe Request wird direkt mit einem RST beantwortet.
  • Danach kommt auf einmal Frame 38 als Quittung von Frame 35.
  • Dann kommt erneut ein RST des Servers.
  • Die Quittierung aus dem ersten Test bleibt aus.

Erst im dritten Test läuft alles, so wie man es erwartet.

  • TCP-Verbindungsaufbau (40,41,42) SYN, SYNACK,ACK
  • MQTT Connect (43) -> TCP-ACK (44) -> MQTT Connect ACK (45)
  • MQTT Subscribe Request (46) -> TCP-ACK (47) -> MQTT Subscribe ACK (48) -> TCP-ACK (49)
  • MQTT Unsubscribe Request (50) -> TCP-ACK (51) -> MQTT Unsubscribe ACK (52)
  • MQTT Disconnect Request (53) -> TCP-ACK (54)-> TCP-FINACK (55) -> TCP-ACK (56) -> TCP-RSTACK (57)

Dieser letzte Mitschnitt lässt sich als Grundlage für die Arduino-Programmierung verwenden.

PUBSUB-Message

Hier habe ich mich auf dem Weg Pub->Broker->Sub, beim Mitschnitt auf die Strecke Broker->Sub begrenzt. Es sind 3 Informationsblöcke interessant.

  1. Ping Request/Response
  2. Publish Message
  3. ARP


2 mal ein Pub auf einen am Client (192.168.2.49) abonnierten Topic (homie)
1 0.000000000 192.168.2.49 192.168.2.1 MQTT 60 Ping Request
2 0.000107425 192.168.2.1 192.168.2.49 MQTT 56 Ping Response
3 0.043663519 192.168.2.49 192.168.2.1 TCP 60 50914 → 1883 [ACK] Seq=3 Ack=3 Win=8212 Len=0
4 9.999400790 192.168.2.49 192.168.2.1 MQTT 60 Ping Request
5 9.999549665 192.168.2.1 192.168.2.49 MQTT 56 Ping Response
6 10.039394210 192.168.2.49 192.168.2.1 TCP 60 50914 → 1883 [ACK] Seq=5 Ack=5 Win=8212 Len=0
7 19.999789083 192.168.2.49 192.168.2.1 MQTT 60 Ping Request
8 19.999902704 192.168.2.1 192.168.2.49 MQTT 56 Ping Response
9 20.040934732 192.168.2.49 192.168.2.1 TCP 60 50914 → 1883 [ACK] Seq=7 Ack=7 Win=8212 Len=0
================
10 23.634020058 192.168.2.1 192.168.2.49 MQTT 72 Publish Message [homie]
11 23.674288745 192.168.2.49 192.168.2.1 TCP 60 50914 → 1883 [ACK] Seq=7 Ack=25 Win=8212 Len=0
================
12 24.530473818 Shenzhen_XX:XX:XX HewlettP_XX:XX:XX ARP 60 Who has 192.168.2.1? Tell 192.168.2.49
13 24.530498729 HewlettP_XX:XX:XX Shenzhen_XX:XX:XX ARP 42 192.168.2.1 is at 1c:c1:de:32:98:c9
================
14 30.000128845 192.168.2.49 192.168.2.1 MQTT 60 Ping Request
15 30.000250227 192.168.2.1 192.168.2.49 MQTT 56 Ping Response
16 30.041465312 192.168.2.49 192.168.2.1 TCP 60 50914 → 1883 [ACK] Seq=9 Ack=27 Win=8212 Len=0
17 40.000709816 192.168.2.49 192.168.2.1 MQTT 60 Ping Request
18 40.000821485 192.168.2.1 192.168.2.49 MQTT 56 Ping Response
19 40.042556378 192.168.2.49 192.168.2.1 TCP 60 50914 → 1883 [ACK] Seq=11 Ack=29 Win=8212 Len=0
20 50.000921223 192.168.2.49 192.168.2.1 MQTT 60 Ping Request
21 50.001061993 192.168.2.1 192.168.2.49 MQTT 56 Ping Response
22 50.042997914 192.168.2.49 192.168.2.1 TCP 60 50914 → 1883 [ACK] Seq=13 Ack=31 Win=8212 Len=0
================
25 53.545514129 192.168.2.1 192.168.2.49 MQTT 72 Publish Message [homie]
26 53.586777037 192.168.2.49 192.168.2.1 TCP 60 50914 → 1883 [ACK] Seq=13 Ack=49 Win=8212 Len=0
================ 
29 60.001538863 192.168.2.49 192.168.2.1 MQTT 60 Ping Request
30 60.001651530 192.168.2.1 192.168.2.49 MQTT 56 Ping Response
31 60.044167558 192.168.2.49 192.168.2.1 TCP 60 50914 → 1883 [ACK] Seq=15 Ack=51 Win=8212 Len=0

Ping Request/Response

Die drei Frames eines Ping Request/Response (1,2,3) wiederholen sich bei (4,5,6), (7,8,9), (14,15,16) usw. alle 10 Sekunden.

Der Ping Request geht vom SubClient aus und dient der Aufrechterhaltung des Connects (Verbindung). Der Standard macht dazu folgende Aussagen:

The Keep Alive is a time interval measured in seconds. Expressed as a 16-bit word, it is the maximum time interval that is permitted to elapse  between the point at which the Client finishes transmitting one Control Packet and the point it starts sending the next. It is the responsibility of the Client to ensure that the interval between Control Packets being sent does not exceed the Keep Alive value. In the absence of sending any other Control Packets, the Client MUST send a PINGREQ Packet [MQTT-3.1.2-23].
The Client can send PINGREQ at any time, irrespective of the Keep Alive value, and use the PINGRESP to determine that the network and the Server are working.
If the Keep Alive value is non-zero and the Server does not receive a Control Packet from the Client within one and a half times the Keep Alive time period, it MUST disconnect the Network Connection to the Client as if the network had failed [MQTT-3.1.2-24].
If a Client does not receive a PINGRESP Packet within a reasonable amount of time after it has sent a PINGREQ, it SHOULD close the Network Connection to the Server.
A Keep Alive value of zero (0) has the effect of turning off the keep alive mechanism. This means that, in this case, the Server is not required to disconnect the Client on the grounds of inactivity.
Note that a Server is permitted to disconnect a Client that it determines to be inactive or non-responsive at any time, regardless of the Keep Alive value provided by that Client.

Anmerkungen aus einem Forum:

If the client is disconnected then yes, it will not receive messages, however there are features in MQTT that work around this.
If the client connects to the server with the 'Clean session' flag set to false, then the server will remember the subscription for that client ID. Once the client reconnects, it will not need to re-subscribe as the server will have remembered it.
Furthermore, you can subscribe using QoS Level 1 or 2. With these QoS Levels, the Server will store messages and wait for the client to reconnect before sending them on. This way, even if the client disconnects and reconnects they will still receive all published messages.

Da bedeutet kurz gefasst. Der Client bestimmt beim Connect selbst den KeepAlive-Zeitraum (In meinem Beispiel sind es 60 Sekunden s.o.). Der KeepAlive-Zeitraum (16 Bit Sekunden) kann also zwischen 0 und 0xFFFF (18 Stunden, 12 Minuten, 15 Sekunden) liegen. Ein KeepAlive von 0 Sekunden hat zudem die besondere Bedeutung, dass der Server kein 'Lebenszeichen' des Clients nach dem Connect mehr benötigt und die Verbindung dauerhaft aufrechterhält. Dummerweise kann aber unabhängig davon ein Server einen Client jederzeit 'disconnecten' wenn er der Meinung ist, dass der Client inaktiv ist. Für einen reinen Publisher ist das jedoch kein echtes Problem. Wenn er eine Message absetzt und vom Server ein 'Disconnected' erfährt kann er sich einfach neu connecten und seine Meldung nochmal absetzen, oder er prüft vor jeder abgehenden Meldung die Verbindung zum Broker (Server). Für einen reinen Subscriber ist das schon dramatischer. Wenn er disconnected ist, ohne dass er es bemerkt, bekommt er einfach keine Nachrichten mehr. Dies ist in der Regel nicht erwünscht. Letztlich hat man dann nur die Möglichkeit in regelmäßigen Abständen mit Ping (TCP und MQTT) die Verbindung zu prüfen und aufrecht zu erhalten, oder den Quality-of-Service-Level der Nachrichten zu erhöhen. Dazu weiter unten mehr.

Ein MQTT-System (z.B. in der Hausautomation) muss ausfallsicher (Strom, Netzwerk, Server, Broker, ...) sein oder nach einer Störung einer der beteiligten Komponenten selbstständig in einen definierten Zustand zurückfinden. Daran kranken viele Implementierungen. Der Grad der Zuverlässigkeit einer (Haus-)Automatisierung bemisst sich im Wesentlichen am Verhalten nach Störungen. Ein Stresstest aller Komponenten führt schnell zur Erkenntnis.

PING Request [ACKPSH] S1A1

0000   1c c1 de 32 98 c9 5c 85 7e 43 11 b4 08 00 45 00   ...2..\.~C....E.
0010   00 2a 32 05 40 00 80 06 43 46 c0 a8 02 31 c0 a8   .*2.@...CF...1..
0020   02 01 c6 e2 07 5b ca af 16 c5 0c ea ee 17 50 18   .....[........P.
0030   20 14 9f 7e 00 00 c0 00 00 00 00 00                ..~........
MQ Telemetry Transport Protocol, Ping Request
   Header Flags: 0xc0, Message Type: Ping Request
       1100 .... = Message Type: Ping Request (12)
       .... 0000 = Reserved: 0
   Msg Len: 0

PING Response [ACKPSH] S1A3

0000   5c 85 7e 43 11 b4 1c c1 de 32 98 c9 08 00 45 00   \.~C.....2....E.
0010   00 2a fb 39 40 00 40 06 ba 11 c0 a8 02 01 c0 a8   .*.9@.@.........
0020   02 31 07 5b c6 e2 0c ea ee 17 ca af 16 c7 50 18   .1.[..........P.
0030   01 f6 85 9f 00 00 d0 00                           ........
MQ Telemetry Transport Protocol, Ping Response
   Header Flags: 0xd0, Message Type: Ping Response
       1101 .... = Message Type: Ping Response (13)
       .... 0000 = Reserved: 0
   Msg Len: 0

Der folgende TCP-Paket ist ein reines Acknowledge des Clients auf die Ping Response.

Publish

Es sei noch einmal kurz darauf hingewiesen, dass es sich hier um eine Nachricht vom Broker zum Client handelt. Weiterhin sei schon mal vorab erwähnt, dass der QoS-Level pro Strecke (Pub->Broker, Broker->Sub) getrennt festgelegt wird. Er gilt also nicht für die Nachricht von der Quelle zum Ziel.

Publish S7A7
0000   5c 85 7e 43 11 b4 1c c1 de 32 98 c9 08 00 45 00   \.~C.....2....E.
0010   00 3a fb 3c 40 00 40 06 b9 fe c0 a8 02 01 c0 a8   .:.<@.@.........
0020   02 31 07 5b c6 e2 0c ea ee 1d ca af 16 cb 50 18   .1.[..........P.
0030   01 f6 85 af 00 00 30 10 00 05 68 6f 6d 69 65 6e   ......0...homien
0040   69 63 65 74 72 79 31 35                           icetry15


MQ Telemetry Transport Protocol, Publish Message
   Header Flags: 0x30, Message Type: Publish Message, QoS Level: At most once delivery (Fire and Forget)
       0011 .... = Message Type: Publish Message (3)
       .... 0... = DUP Flag: Not set
       .... .00. = QoS Level: At most once delivery (Fire and Forget) (0)
       .... ...0 = Retain: Not set
   Msg Len: 16
   Topic Length: 5
   Topic: homie
   Message: 6e6963657472793135

Das folgende TCP-Paket (S7A25) ist ein reines Acknowledge des Clients auf das Publish-Paket.

ARP

An dieser Stelle will ich keine neue Abhandlung zu ARP schreiben, aber vielleicht ein paar Klarstellungen und Überlegungen zur Implementierung in einem Mikrocontroller-Client aufzeigen.

ARP liegt im ISO/OSI in Schicht 2 und im TCP/IP in der Netzzugangsschicht (1) und hat damit erstmal nicht zwingend was mit TCP/IP zu tun. Die RFC826 gibt dazu den entsprechenden Hinweis:

Converting Network Protocol Addresses to 48.bit Ethernet Address for Transmission on Ethernet Hardware
The purpose of this RFC is to present a method of Converting Protocol Addresses (e.g., IP addresses) to Local Network Addresses (e.g., Ethernet addresses).

Das Exempli Gratia 'IP addesses' wird eindeutig als Beispiel und damit als ein Anwendungsfall unter weiteren Möglichen genannt.

Lässt man ARP erst mal außer Acht, ergibt sich beim Zusammenbauen eines Ethernetframes in der Firmware eines uPC die Notwendigkeit sowohl die eigene Ethernet-Adresse als auch die Ethernet-Adresse des Frame-Empfängers einzutragen. Die eigene Ethernet-Adresse (MAC) ist bekannt. Sie ist in der Regel im Ethernet-Controller oder in der Firmware (Treiber) fest hinterlegt. Die Ethernet-Adresse (MAC) des Zielrechners kennt man erst mal nicht. Befinden sich alle Kommunikationspartner mehr oder minder unverändert über einen längeren Zeitraum (z.B. Jahre) im gleichen Netzsegment könnte man auf die Idee kommen, alle in einem Netzsegment vorkommenden MAC/IP-Paare in einer Liste zu erfassen und in der Firmware zu hinterlegen. Da bei einem MQTT-Pub/Sub-Client nur der Broker (Server) von Interesse ist, würde die Liste sogar nur aus einem Eintrag bestehen. Man könnte also bei der Implementierung des MQTT-Clients bei den Setup-Parametern mit der IP des Borkers (Servers) die passende MAC gleich mit hinterlegen. Das hätte den angenehmen Vorteil, dass man sich über ARP-Spoofing/Poisoning/Flooding keinen Kopf zerbrechen müsste. Ein Nachteil wäre sicherlich, die Notwendigkeit bei einem Server/Broker-Wechsel alle beteiligten Clients neu zu konfigurieren. Sollte sich der Broker nicht im gleichen Netzsegment befinden würde im MQTT-Client aber auch die MAC-Adresse des Routers (IP-Gateway) genügen.

MQTT Paketaufbau

Alle Control Pakets im Überblick

Paketaufbau im Detail
Kommando Aufbau
Name Value Direction
of flow
Description Fixed Header Variable Header Payload
  Byte 1
(Bit4-7)
Byte 1
(Bit0-3)
2-5 Byte
(Len1-4)
Byte 3+
(Len-1)
Byte 4+
(Len-1)
Byte 5+
(Len-1)
...
  Control Packet
Type
Control Packet
Flags
Remaining
Length Field
Packet Identifier
MSB
Packet Identifier
LSB
...
Reserved 0 Forbidden Reserved - - - - -
CONNECT 1 C->S Client request to connect to Server 0001 0000 calc special (10 Bytes) Required
CONNACK 2 S->C Connect acknowledgment 0010 0000 0x02 special (2 Bytes) -
PUBLISH 3 C<->S Publish message 0011 XXXX calc YES(QoS>0) Optional
PUBACK 4 C<->S Publish acknowledgment 0100 0000 0x02 YES -
PUBREC 5 C<->S Publish received (assured delivery part 1) 0101 0000 0x02 YES -
PUBREL 6 C<->S Publish release (assured delivery part 2) 0110 0010 0x02 YES -
PUBCOMP 7 C<->S Publish complete (assured delivery part 3) 0111 0000 0x02 YES -
SUBSCRIBE 8 C->S Client subscribe request 1000 0010 calc YES Required
SUBACK 9 S->C Subscribe acknowledgment 1001 0000 calc YES Required (4 values)
UNSUBSCRIBE 10 C->S Unsubscribe request 1010 0010 calc YES Required
UNSUBACK 11 S->C Unsubscribe acknowledgment 1011 0000 0x02 YES -
PINGREQ 12 C->S PING request 1100 0000 0x00 - -
PINGRESP 13 S->C PING response 1101 0000 0x00 - -
DISCONNECT 14 C->S Client is disconnecting 1110 0000 0x00 - -
Reserved 15 Forbidden Reserved - - - - -

Ein Besonderheit bilden die Flags des PUBLISH-Kommandos. Dort können von Bit 3 an folgende 4 Bits gesetzt werden.

  • DUP (Bit 4) Duplikat eines bereits gesendeten PUBLISH Control Pakets
  • QoS (Bit 5-6) Angabe des Levels
  • RETAIN (Bit 7) Die Nachricht soll aufbewahrt werden.

DUP: Das DUP-Flag dient dazu dem Broker/Subscriber zu signalisieren, dass diese Nachricht schon einmal gesendet (published) wurde. In der Spezifikation gibt es einen Hinweis, dass das Flag nur bei QOS 1 oder 2 von Bedeutung ist. Das liegt wohl daran nur bei QOS=1|2 eine Speicherung der Nachricht bis zum ACK stattfindet. Wuerde das DUP-Flag also nicht gesetzt, wuerde das zu einer weiteren Speicherung fuehren.

QOS:siehe unten

RETAIN: Wenn ein Publischer eine Nachricht sendet und (gleichzeitig) kein Subscriber den Topic "abonniert" hat wird die Nachricht vom Server (Broker) verworfen. Es wird immer nur eine Nachricht pro Topic aufbewahrt. D. h erst eine neue retainte Nachricht mit NULL als Inhalt loescht/ueberschreibt eine retainte Nachricht. Dabei ist wohl unerheblich, von welchem Client der Publish kommt. So koennte auch ein Subscriber eine retainte Nachricht loeschen. Getestet habe ich das noch nicht, aber eine entsprechende Option (--remove-retained) in mosquitto_sub (SUB!) laesst darauf schleiszen. Zum erzeugen der NUULL-Nachricht hat mosquitto_pub die Option '-n'. RETAIN ist ideal fuer Statusmeldungen eines Devices. Der (letzte) Status bleibt erhalten und ist auch zeitversetzt noch erhaltbar (sorry mir ist kein besseres Wort eingefallen). Besser finde ich den Einsatz von RETAIN aber noch bei unzuverlaessig angebundenen Devices (alle Arten von Funk, ...) oder welche erst fuer eine Aktivaet aus dem DeepSleep/StandBy geholt werden muessen oder gar erst gestartet werden muessen. Beispiel: Ein Funk-Schaltaktor ist stromlos. Nach dem Einschalten beginnt der Bootprozess und die Kontaktaufnahme (z.B. WLAN) dauert bei einem ESP8266 ca. 10 Sekunden. Diese 10 Sekunden muesste eine Publisher warten bis er erkennt, dass der Schaltaktor bereit ist um seine Nachricht zu senden. Mit Retain kann er sie zeitgleich mit dem PowerUp absetzen und sobald der Schaltaktor aktiv ist erhaelt er seine Nachricht(en). Da pro Topic immmer nur eine Nachricht retained sein kann empfiehlt es sich topics aufzuschluesseln und moeglichst nur einen Wert/Nachricht daran zu senden. D.h. also nicht alle Werte eines Teilnehmers in einen Topic, sondern jeweils einen "Untertopic" fuer z.B. Temperatur, Feuchte, Status, ... und dann dort die Wert hineinsenden.

Remaining Field

In diesem Feld befindet sich die Anzahl der noch 'verbleibenden' Bytes. Also die Anzahl der Bytes ab der Position nach der Längenangabe, die 1 bis 4 Bytes lang sein kann. Da die Längenangabe variabel auf bis zu 4 Bytes verteilt ist, benötigt man einen Mechanismus an dem man sich wie an einer Kette entlanghangeln kann und entscheiden kann, ob noch ein weiteres Längenbyte nachfolgt oder nicht. Dazu wird das MSB (LSB0-Schreibweise) als Flag benutzt. Hat das Bit 7 den Wert 0 folgt kein weiteres Längenbyte. Hat das Bit 7 den Wert 1 muss ein weiteres Byte ausgewertet werden, um die Länge zu bestimmen.

Im Überblick:
Länge zwischen [] Bemerkung 1. Byte 2. Byte 3. Byte 4. Byte
0 127 (2^7-1) kann mit einem Byte gebildet werden 0x00 bis 0x7F - - -
128 (2^7) 16.383 (2^14-1) kann mit zwei Bytes gebildet werden 0x80 bis 0xFF 0x01 bis 0x7F - -
16384 (2^14) 2.097.151 (2^21-1) kann mit drei Bytes gebildet werden 0x80 bis 0xFF 0x80 bis 0xFF 0x01 bis 0x7F -
2097152 (2^21) 268.435.455 (2^28-1) kann mit vier Bytes gebildet werden 0x80 bis 0xFF 0x80 bis 0xFF 0x80 bis 0xFF 0x01 bis 0x7F

Die Längenangabe steht somit in umgekehrter Reihenfolge in den 1 bis 4 Bytes kodiert. Die maximale Länge ergibt sich dadurch zu 256 MiB (ggf. inklusive 2 Bytes Packet Identifier).

Rechenweg von Längenbytes zu Dezimal (Dekodierung)

      multiplier = 1
      value = 0
      do
           encodedByte = 'next byte from stream'
           value += (encodedByte AND 127) * multiplier
           multiplier *= 128
           if (multiplier > 128*128*128)
              throw Error(Malformed Remaining Length)
      while ((encodedByte AND 128) != 0)

Rechenweg von Dezimal zu Längenbytes (Kodierung)

      multiplier = 1
      value = 0
      do
           encodedByte = 'next byte from stream'
           value += (encodedByte AND 127) * multiplier
           multiplier *= 128
           if (multiplier > 128*128*128)
              throw Error(Malformed Remaining Length)
      while ((encodedByte AND 128) != 0)


Kleines Konvertierungstool in C

Code herauskopieren. In Editor einkopieren. Abspeichern als mqttremainlength.c und kompilieren mit

gcc -o mqttremainlength mqttremainlength.c -lm 


mqttremainlength.c
  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <string.h>
  4 #include <errno.h>
  5 #include <limits.h>
  6 #include <stdbool.h>
  7 #include <math.h>
  8 
  9 void usage(){
 10     printf("MQTT Remain Field Value Calculator V0.9 Tibb(at)clx.de\nUsage: \t\tmqttremainlength <decimal>\t\t\t\t\t\t\t\tto convert to field values\n\t\tmqttremainlength <field value 1> <field value 2> <field value 3> <field value 4>\tto convert to decimal\n\nOptions:\t<decimal>\t\ta decimal value from 0 to 268435455\n\t\t<field value x>\t\teach fom 0x01 to 0xFF (omitted values equals to 0x00; erased followflag (bit7=0) extinguish all further values)\n\n");
 11 }
 12 
 13 
 14 bool twohexdigits(char *str){ // test an argument to the format 0x00 - 0xFF or 0xff
 15     if(strncmp(str,"0x",2) == 0 && strlen(str) == 4){
 16         return true;
 17     }
 18     return false;
 19 }
 20 
 21 
 22 int hextodec(char *str){
 23     unsigned int i, len, digitvalue, decimal;
 24     decimal=0;
 25     len=strlen(str);
 26     for(i=0;i<len;i++){
 27         if (str[i]>='0' && str[i]<='9') digitvalue=str[i]-48;
 28         else if (str[i]>='a' && str[i]<='f') digitvalue=str[i]-87;
 29         else if (str[i]>='A' && str[i]<='F') digitvalue=str[i]-55;
 30         decimal+=digitvalue*pow(16,(len-(i+1)));
 31     }
 32     return decimal;
 33 }
 34 
 35 int main(int argc, char *argv[]) {
 36    unsigned int i, decimal, encoded, multiplier, elements;
 37    char null[]="0";
 38    char *endptr = NULL;  
 39    char *argv_ptr = NULL;
 40    bool detect;
 41    char fieldvalue[4][3];
 42 
 43 #ifdef DEBUG
 44    for(i=0; i < argc; i++) {
 45       printf("argv[%d] = %s ", i, argv[i]);
 46       printf("\n");
 47    }
 48    return EXIT_SUCCESS;
 49 #endif
 50 
 51     if(argc==1){  // there is no argument given so print out usage and exit
 52         usage();
 53         return EXIT_SUCCESS;
 54     }
 55 
 56     if(argc==2 && !strncmp(argv[1],"0x",2) == 0){ // there is one argument assume it is a decimal number and conversion asked is decimal to fieldvalue(s); is argument in hex format -> continue below
 57         detect=false;
 58         for (i=0 ; i<strlen(argv[1]); i++){  // also possible with regexp, but don't use a sledgehammer to crack a nut
 59             argv_ptr = argv[1] + i;
 60             if (strncmp(argv_ptr,"0",1) == 0) detect=true;
 61             if (strncmp(argv_ptr,"1",1) == 0) detect=true;
 62             if (strncmp(argv_ptr,"2",1) == 0) detect=true;  
 63             if (strncmp(argv_ptr,"3",1) == 0) detect=true;
 64             if (strncmp(argv_ptr,"4",1) == 0) detect=true;
 65             if (strncmp(argv_ptr,"5",1) == 0) detect=true;  
 66             if (strncmp(argv_ptr,"6",1) == 0) detect=true;
 67             if (strncmp(argv_ptr,"7",1) == 0) detect=true;
 68             if (strncmp(argv_ptr,"8",1) == 0) detect=true;    
 69             if (strncmp(argv_ptr,"9",1) == 0) detect=true;
 70             if (!detect){
 71                 usage();
 72                 printf("Error 1: Value %s seems not to be a regular decimal number!\n", argv[1]);
 73                 return EXIT_FAILURE;
 74             }
 75             detect=false;
 76         }
 77 
 78         errno = 0;
 79         decimal=strtoul(argv[1],&endptr,10);
 80         if (argv[1] == endptr){
 81                 printf ("Error 2: Value %s seems not to be a decimal number!\n", argv[1]);
 82                 return EXIT_FAILURE;
 83         }
 84         else if (errno == ERANGE && decimal == LONG_MIN){
 85                 printf ("Error 3: Value %s is an invalid number! (underflow)\n", argv[1]);
 86                 return EXIT_FAILURE;
 87         }
 88         else if (errno == ERANGE && decimal == LONG_MAX){
 89                 printf ("Error 4: Value %s  is an invalid number! (overflow)\n", argv[1]);
 90                 return EXIT_FAILURE;
 91         }
 92         else if (errno != 0 && decimal == 0){
 93                 printf ("Error 5: Value %s seems not to be a decimal number!\n", argv[1]);
 94                 return EXIT_FAILURE;
 95         }
 96         else if (errno == 0 && argv[1] && !*endptr){
 97             if (decimal>268435455){
 98                 printf ("Error 6: Value greater than allowed! (MAX: 268435455)\n", argv[1]);
 99                 return EXIT_FAILURE;               
100             }
101             else{
102                 printf("Decimal Value: %s\t",argv[1]);
103                 printf("Field Value(s): ");
104                 do {
105                     encoded = decimal % 128;
106                     decimal = decimal / 128;
107                     if ( decimal > 0 ){
108                         encoded = encoded | 128;
109                     }
110                     printf("0x%02x\t",encoded);
111                 }
112                 while ( decimal > 0 );
113                 printf("\n");
114                 return EXIT_SUCCESS;
115             }
116         }
117         else if (errno == 0 && argv[1] && *endptr != 0){
118                 printf ("Error 7: Value %s seems not to be a decimal number!\n", argv[1]);
119                 return EXIT_FAILURE;
120         }
121      }
122     
123     if(argc>1 && argc<=5){
124         detect=false;
125         elements=0;
126         for(i=1; i < argc; i++) {// test each argument to compliant notation
127             if (!twohexdigits(argv[i])) detect=true;
128             strncpy(fieldvalue[i-1],argv[i]+2,2);
129             fieldvalue[i-1][2]='\0';
130             elements++;
131         }
132         if (detect){
133             usage();
134             printf("Error 8: Field Values seem not to be in expected Format e. g. 0x00, 0x1F, 0xab, ...\n");
135             return EXIT_FAILURE;
136         }
137         if (elements>=1) i=elements;
138         decimal=0;
139         detect=false;
140         do{
141             i--;
142             multiplier=pow(2,i*7);
143             encoded=hextodec(fieldvalue[i]);
144             if ((encoded & 128)==128 && i == (elements-1)) detect=true;
145             else if ((encoded & 128)==0 && i < (elements-1)) detect=true;
146             else decimal+= (encoded & 127) * multiplier; 
147         }
148         while(i>0);
149         if (detect){
150             printf("Error 9: Follow Flags in Field Values seem not to be correct!\n");
151             return EXIT_FAILURE;           
152         }
153         else{
154             printf("Field Values:");
155             for(i=1; i < argc; i++) {
156                 printf("%s ",argv[i]);
157             }
158             printf("Decoded Value: %d\n",decimal);
159             return EXIT_SUCCESS;
160         }
161     }
162     return EXIT_FAILURE;
163 }

Quality of Service

Wie weiter oben schon mal kurz erwähnt kann die Quality of Service (QoS) auf der Strecke vom Publisher zum Broker in der Publish-Nachricht im Fixed-Header als 2-Bit-Flag mitgegeben werden. Der empfangende Client kann seinerseits im Subscribe angeben mit welchem QoS er einen Topic empfangen will. Richtig gute Illustrationen, die einem bei der Implementierung helfen, habe ich bei meinen Recherchen nur wenige gefunden. Daher habe ich nachfolgend erst mal die wichtigsten Zusammenhänge zusammengefasst.


QoS auf dem Weg vom Client (Publish)->Server->Client(Subscribe)
Fall QoS of PUBLISH QoS of SUBSCRIBE QoS of received Message
1 0 0 0
2 0 1 0
3 0 2 0
4 1 0 0
5 1 1 1
6 1 2 1
7 2 0 0
8 2 1 1
9 2 2 2

Die Regeln hinter der Anpassung des QoS durch den Server lauten damit:

  1. Der QoS ist maximal gleich dem Client-Publish (QoS des Client-Publish ist für die Wert-Obergrenze dominant)
  2. WENN QoS(Publisher) >= QoS(Subscriber) DANN QoS(Subscriber) (Fälle: 1,4,5,7,8,9)
  3. WENN QoS(Publisher) < QoS(Subscriber) DANN QoS(Client) (Fälle: 2,3,6)

MQTT QoS0 Diagramm.png

MQTT QoS1 Diagramm.png

MQTT QoS2 Diagramm.png

Last Will

Sozusagen das Testament oder auch letzter Wille genannt ist die Moeglichkeit eines Clients beim Connect beim Borker (sozusagen Notar) eine Nachricht zu hinterlegen die in einem Fall eines unerwarteten Disconnects gesendet (normaler publish) wird. Damit koennen die Subscriber der Topics ueber die Kommunikationsunterbrechung informiert werden. Ein "normaler" Disconnect loescht den Last Will beim Broker und muss beim Connect wieder neu angelegt werden.

Weitere Quellen

http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html

https://docs.solace.com/MQTT-311-Prtl-Conformance-Spec/MQTT%20Control%20Packets.htm#_Toc430864912

http://www.steves-internet-guide.com/understanding-mqtt-qos-2/

https://www.informatik-aktuell.de/betrieb/netzwerke/mqtt-leitfaden-zum-protokoll-fuer-das-internet-der-dinge.html

https://www.ibm.com/support/knowledgecenter/de/SSFKSJ_7.5.0/com.ibm.mq.pro.doc/q001010_.htm

https://www.msxfaq.de/sonst/iot/mqtt.htm

https://medium.com/@emqtt/introduction-to-mqtt-5-0-protocol-qos-quality-of-service-e6d9b0aaf9fb

https://smart-home-assistant.de/mqtt-grundlagen/

https://tinkerman.cat/post/mqtt-topic-naming-convention

Request for Comments


Kommentar hinzufügen
TippvomTibb freut sich über alle Kommentare. Sofern du nicht anonym bleiben möchtest, registriere dich bitte oder melde dich an.