Using The Mosquitto_pub and Mosquitto_sub MQTT Client Tools- Examples

The Mosquitto_pub and Mosquitto_sub client utilities comes with the Mosquitto package, and are excellent tools for conducting quick tests and troubleshooting..

In this tutorial we are going to be looking at some examples of using these tools for publishing and subscribing.

Publishing Using The Mosquitto_pub Client

The screen shot shot below shows a simple publish, and a publish with the debug flag (-d) set.

using-mosquito_pub-client

In the first example the message is published and the client exits without displaying any messages.

If you enable the debugging using the -d flag then you can see the connect,publish and disconnect messages.

Notice the -h flag sets the host name or IP address. To get help use the –help flag.

e.g. mosquitto_pub –help

Useful Flag Options and Examples

-r  Sets retain flag
-n  Sends Null message useful for clearing retain message.
-p – Set Port number Default is 1883
-u – Provide a username
-P – Provide a password
-i – Provide client name
-I – Provide a client id prefix- Used when testing client restrictions using prefix security.

Publish With Username and Password

Uses -u username and -P password flags

mosquitto_pub-example-1

Publish with Retain Flag

Uses -r Flag

mosquitto_pub-example-2

Clear Retained Message

Uses the -r -n flag combination

mosquitto_pub-example-3

Publish with Client Name

This  option is useful when testing client restrictions using prefixes or client names with ACLs.

Uses -i option. You could also use the -I option if you just needed prefixes.

mosquitto_pub-example-4

Publishing JSON Data

JSON Data has a special format described here. When is comes to publishing with the mosquitto_pub client you need to escape the quotes so that they are included.

So don’t use {“status”:”off”} but instead use: {\”status\”:\”off\”}.

mosquitto-pub-json-data
If you are sending multiple values then you need to put the entire string in quotes:

mosquitto_pub -h localhost -t test -m "{\"value1\":20,\"value2\":40}"

On Linux you can also use shell variables. If you have a shell variable called var1 then:

mosquitto_pub -h localhost -t test -m "{\"value1\":20,\"value2\":$var1}"

Mosquitto_pub -Publish Using SSL

Note: you will need to copy the CA.crt file into the appropriate directory. Use the –insecure switch if the name on the certificate doesn’t match the actual broker name.

mosquitto_pub-ssl

Notes
There is also a option to publish a will message using the –will-topic flag but I couldn’t get this to work.

Using The Mosquitto_sub Client

This is useful for quickly monitoring a topic. Flag options are mostly the same as the mosquitto_pub client.

When you start this client it runs indefinitely until stopped using CTRL+C.

mosquitto-sub-client-example

A useful option is the -C flag which will disconnect after receiving a certain number of messages.

mosquitto-sub-client-example-2

Using the -v  (verbose option will show the topic name as well as the message.

mosquitto_sub-v

The debug option -d flag is useful when you want to see the messages flags like qos and retain flag.

mosquitto-sub-client-example-3

You can change the QOS when subscribing using the -q switch.

mosquitto-sub-qos

Subscribing to all topics

You can use the wildcard character to subscribe to all topics but you must use a delimiter.

mosquitto_sub -h localhost -t \# -d

Notes:

    • I didn’t get the scripts to work on Windows XP -Error not a valid win32 application

 

    • On Windows 7 and 10 they gave an error regarding a missing msvcr100.dll file. I found the file on my system and copied it to the Mosquitto directory and they worked OK.

References: Here is the pub manual page, and here is the sub manual page.

Using in Bash Scripts

You can use the mosquitto_pub and sub tools inside bash scripts. Below I use mosquitto_pub to publish a JSON string with the username set as a bash variable

mosquitto_pub -h localhost -t test -m "{\"user\":$USER}"

Video- Using the mosquitto_pub and mosquitto_sub client tools

Testing With IPv6

Any computer configured to support IPV6 (almost all are today) will have several IP addresses by default.

The IP address types are:

  • Global Unicast Address
  • Unique Local
  • Link Local

and are described in more detail in the IPv6 tutorial

The addresses used on the local network are the unique local and the link local whereas the global address can be used by an external client to access the computer.

When testing on the internal network you can use all three as shown below:

mosquitto-test-ipv6

 

Summary

The mosquitto_pub and mosquitto_sub client utilities are excellent tools for testing and troubleshooting MQTT and broker problems.



Other Related Articles and Resources:

Special Note for windows users:If you use windows you can get these tools by installing the mosquitto broker on windows or downloading my windows package which contains these tools as well as the broker. The tools as well as the broker work without requiring an install.

Please rate? And use Comments to let me know more

103 comments

  1. Hi Steve,
    obviously I don’t understand how to use mosquitto_sub properly.
    I want to read sensor data from a Lidl HG08673 and process it further in a script.

    mosquitto_sub -h localhost -t zigbee2mqtt/Lidl/# supplies
    online
    {“child_lock”:”UNLOCK”,”current”:0.03,”device”:{“applicationVersion”:68,”dateCode”:””,”friendlyName”:”Lidl”,”hardwareVersion”:1,”ieeeAddr”:”0xa4c138fa4b44aeb0″,”manufacturerID”:4417,”manufacturerName”:”_TZ3000_j1v25l17″,”model”:”HG08673″,”networkAddress”:16319,”powerSource”:”Mains (single phase)”,”stackVersion”:0,”type”:”Router”,”zclVersion”:3},”energy”:20.69,”indicator_mode”:”off/on”,”linkquality”:255,”power”:6,”power_outage_memory”:”off”,”state”:”ON”,”voltage”:234}

    whereas mosquitto_sub -h localhost -t zigbee2mqtt/Lidl/power
    doesn’t return anything.

    Would you be able to help? What am I doing wrong?
    TIA, Michael

    1. You need to subscribe and use the -d switch to see the topic as well as the payload
      mosquitto_sub -h localhost -t zigbee2mqtt/Lidl/# -d

      You will probably find that it is publishing on another topic not power.
      rgds
      steve

      1. Thanks for your reply.
        To be honest, I did that before, this is the diff between the two calls:
        Client (null) sending CONNECT <
        Client (null) received CONNACK (0) <
        Client (null) sending SUBSCRIBE (Mid: 1, Topic: zigbee2mqtt/K <
        Client (null) received SUBACK <
        Subscribed (mid: 1): 0 <
        Client (null) received PUBLISH (d0, q0, r1, m0, 'zigbee2mqtt/ <
        online online
        Client (null) received PUBLISH (d0, q0, r0, m0, 'zigbee2mqtt/ <
        {"child_lock":"UNLOCK","current":0,"device":{"applicationVers {"child_lock":"UNLOCK","current":0,"device":{"applicationVers
        Client (null) sending DISCONNECT <

        I can't see anything much beside the "child_lock", I guess that's not what I am looking for?
        Is it possible to use MQTT-Explorer or the zigbee2mqtt-GUI to extract the required call?
        Thanks, Michael

  2. Hello Steve,

    I want to use 2 devices (Linux – fedora) for implementing the MQTT protocol using the mosquitto.
    Now i have downloaded the mosquitto in both the devices, can you please help me implementing this scenario

    1. Hi
      You only need one mosquitto broker. The other devices will be clients and you can implement them all on a single machine or use one machine as the broker and put the clients on the other machine.
      Does that make sense.
      Rgds
      Steve

      1. Hello Steve,
        Sorry for the late reply.

        Having Broker, publisher in one device and subscriber in another device works for me.
        I will give you the whole scenario how I’m trying it.
        In a single device if i bring-up all the broker, publisher, client it works fine. In this scenario I’m using publisher with localhost and static IP. From the subscriber side i will either localhost or Static IP according to my implementation in Publisher. (No issues/problems faced in this scenario).

        Now The problem I’m facing is:
        In Device 1: i have created a broker and publisher. For the publisher i have used the static ip which i have assigned. (192.168.xx.xx).
        In Device 2: i want this device to act as subscriber, and receive messages from the publisher who is on other device (for example having a static IP 192.168.xx.yy).

        Regards,
        newbee.

        1. The only IP address that is important is the iP of the broker. Both clients must subscribe/publish to this address. Does that make sense?
          Rgds
          Steve

  3. Hi Steve
    Thank you very much for your tutorial. I am a beginner and I have problems for sending some characters like “:” (for timestamp or mac address) or spaces in the names. How to solve it ??

    I am using this command in an BashScript:

    mosquitto_pub -d -q 1 -h $_server -p 1883 -t v1/devices/me/telemetry -u $_token -m “{dev_mac:$_mac_address}”

    If I change the “:” for “_” it works … but I need the MacAddress or the timestamp.

    Thank you very much.

    Best regards
    A.

    1. try using the backslash infront of the character e.g
      \:
      let me know if it works or not and what OS you are using.
      Rgds
      Steve

  4. Hello Steve, I am running MQTT and NodeRed on a Pi with a weather station connected on USB port.
    For that i got a tool te923con.h . When i execute it in bash it sends all sensor data like
    1678169310:20.65:40:20.20:42:15.10:23:7.90:39:i:i:20.10:41:978.6:i:2:0:14:0.0:0.0:8.0:0
    How can i pipe that into a into a mosquitto_pub statement directly for -m?
    And then maybe all 10min.
    Sorry i have little experiance.
    Thanks
    Michael

    1. Hi
      There is a -f option to read from a file so you could send the output of the script to a file and then read it.
      There is also a –repeat and also a –repeat-delay which you need to use together.
      You could also run the mosquitto in a script . You might find this useful
      https://funprojects.blog/2021/05/25/bash-with-mqtt/

      I did do a script some time ago but can’t find it. I will try and put something together if you get stuck so let me know.
      Rgds
      Steve

  5. For Test purpose, I already have a publisher device with me. But i need to give the broker URL, username and password in it. How can i do that? where will i get moquitto broker details? In my test case the subscriber client will be Azure. Please help.

    1. The broker can be any MQTT broker. If you don’t have one you can use the public text brokers like
      test.mosquitto.org
      rgds
      steve

  6. Hello Steve,
    I have a Scada Software that does not understand values with quotes in between them. So example My device send a json A schema string with multiple values Temp, battery, rssi, and humidity they all have quotes in between them. I used a command line that I can remove the quotes. Is there a way mosquitto can remove the quotes from the values so my scada software understands the language?

    1. No mosquitto transfers messages and doesn’t care about message content.
      The easiest way is to use a client e.g python to subscribe to the data and then republish it without the quotes.
      Rgds
      Steve

  7. Hi Steve,
    I am trying to run the mosquitto client ‘mosquitto_sub’ on a xubuntu machine to connect to a private IP. Following is the command i give on the linux prompt:
    mosquitto_sub -v -L “mqtts://user:xxxpasswdxxx@mqtt.mydevportal.com:8883/server/LG01020105272100006/#” -V mqttv311 –insecure –cafile “/media/sf_SharedFolder/cert_ecc/rootca.pem” –capath “/media/sf_SharedFolder/cert_ecc” –cert “cert.pem” –key “pkey.pem” –keyform “pem” –tls-version tlsv1.2

    I get the following error:
    Error: Problem setting TLS options: File not found.

    Please guide me where am I going wrong with the command.

  8. HI,
    while working with MQTT I want to publish the message if connected else if MQTT is not connected then have to write the message to the shell script. all these processes will be through shell script can i get any clue on how to detect whether MQTT is connected or not?

  9. Steve, I am new to the MQTT world and am part of a design team on a project with multiple processors, each of which is expected to run a broker. I haven’t seen anything yet on how to connect multiple brokers in a system. Can you help me out?

  10. Hi Steve. Thanks: excellent job!
    Could you please clarify (-insecure option) your: “name on the certificate doesn’t match the actual broker name.”
    The mosq_pub manual calls the “broker name” a “server hostname” – not very informative too. Is it a machine name the Mosquitto runs on?

    Now a question (maybe to the author):
    The Mosquitto server, and the clients discussed here print diagnostic messages translated to a language of the area the computer is located (configured to). Unfortunately not always this is done correct.
    So, isn’t there an option to disable translation (pretend you are in England, or just do not understand foreign languages)? I did not find anything in the manuals (maybe missed).

    1. On your first point.
      On an ip network to get to a machine/host you can always use the IP address of that machine. You can also use a domain name or partial domain name depending on how the network is configured.
      On windows networks just using the computer name works.
      When you connect to a broker you will use and IP address or name(if possible). When configuring a certificate for a broker you need to set the common name to the name/address the MQTT client will use to connect to that broker otherwise you get an error as the client will compare the name on the certificate to the name you are using to access the broker.
      The -insecure option disables this check.
      Does that make more sense?
      On the language issue I use mosquitto on a broker in England so wasn’t aware of this issue I will try to find out. Just drop me a reminder if I haven’t got back.
      Rgds
      Steve

  11. Hi Steve,

    I’ve encountered a problem which I can’t find a solution or explanation for it, I thought perhaps you have encountered this issue yourself:

    I have a broker hosted in flepsi.io, all is working well and I’m quite happy with their service; when I use the following command on my Linux machine I connect to the broker with no issues:
    mosquitto_sub -L mqtts://NotMyRealToken@mqtt.flespi.io:8883/# -v

    when I try the exact same command on my windows machine, I get the following error:
    Error: A TLS error occurred.

    I’ve made sure no VPN is running and the firewall is closed and yet I get the above error message.
    any thoughts on why this doesn’t work under the windows machine?

    Thanks much in advance!
    Ram

      1. correct, according to their support no –cafile is needed and it does connect without ca file when I ran the same command in a Linux machine via WebSockets successfully.

        1. Do they mention Windows? It might be that you need to specify the ca file on windows. Can you point me to the help on their website.
          Rgds
          Steve

          1. Hi
            Sorry been busy with other things. Do you have an update or is it still not working?
            Rgds
            Steve

  12. Hello Steve, we are formatting hexadecimal data as shown here (“\x45\x23\x43\x00\x45\x22”) and sending it using mosquito_pub tool. The problem here is \x00 is interpreted as end of data rather than data itself. Is there a better way to send hexadecimal data using mosquito_pub.

    1. The tool is sending a string and not hexidecimal data it will need to be interpreted at the other end. What do you see at the receiver? are you using C at the receiver as \x00 is end of string indicator?
      Rgds
      Steve

  13. Hi Steve,
    Is there a way to simulate a zigbee sensor/button?
    I am building a domoticz environment for somebody else, I have a remote connection but cannot ask them to push a button everytime.

    In the zigbee2mqtt log this is a push of a button:
    info 2021-11-27 15:45:25: MQTT publish: topic ‘zigbee2mqtt/switch01’, payload ‘{“action”:”left_double”,”battery”:86,”linkquality”:31,”voltage”:2975}’

    So question is if there is a possibility with mosquito_pub to simulate such a message, so to test without that actually anybody pushes a button.

    Thanks,
    Jan-Pieter

    1. Yes you can I do it all the time. I prefer to use a python script or node red if I need to do it often as it is easier.
      When using the mosquitto_pub tool you need to delimit it which can be tricky as it varies on windows and linux.Once you get it working copy it to a text files so you can reuse later.

      If you are stuck let me know and I will try it for you just let me know what OS windows or linux.
      Rgds
      Steve

      1. I tried:
        mosquitto_pub -d -r -q 1 -u domoticz -P pass -t zigbee2mqtt/switch01/set -m “{\”action\”:\”left_double\”}”

        But I get the following in the zigbee2mqtt log:
        error 2021-11-28 23:28:44: No converter available for ‘action’ (left_double)

        So this way the command is trying to send to the device, which of course does not recognize it as a device setting… So how to publish to the topic as it was reported by the switch/sensor ?

        Kind regards,
        Jan Pieter

        1. Hi
          I tested this on windows and linux
          mosquitto_pub -h 192.168.1.51 -t test -m “{\”action\”: \”left_double\”, \”battery\”: 86,\”linkquality\”: 31,\”voltage\”: 2975}”
          rgds
          steve

  14. Hi Steve, thank you so much for the tutorial. I downloaded your quick install for Windows v2 file, but there’s no mosquitto_sub.exe in it. I had to download a v1.6.9 file and extract the sub file to the v2 folder.

  15. Hi Steve, thanks for the great tutorial 🙂
    I’m currently having an issue where I’m not seeing any of my published messages in my sub window. Which puzzles me because the debugger did not indicate any connection problems.

    Sub window:
    C:\Program Files\mosquitto>mosquitto_sub -h 10.10.20.126 -t testing/# -d -v
    Client (null) sending CONNECT
    Client (null) received CONNACK (0)
    Client (null) sending SUBSCRIBE (Mid: 1, Topic: testing/#, QoS: 0, Options: 0x00)
    Client (null) received SUBACK
    Subscribed (mid: 1): 0
    Client (null) sending PINGREQ
    Client (null) received PINGRESP

    Pub window:
    C:\Program Files\mosquitto>mosquitto_pub -h 10.10.20.126 -t testing/example -m “hello” -d -r -q 1
    Client (null) sending CONNECT
    Client (null) received CONNACK (0)
    Client (null) sending PUBLISH (d0, q1, r1, m1, ‘testing/example’, … (5 bytes))
    Client (null) received PUBACK (Mid: 1, RC:0)
    Client (null) sending DISCONNECT

    1. Hi
      Do you have access to the broker console if so do you see the publish?
      If the broker has ACL restrictions then you are not notified and the broker just drops the packet. Is t your broker?
      Your commands look ok.
      Rgds
      Steve

  16. Hey Steve,
    Nice tutorial

    mosquitto_pub -h localhost -t test -m “{\”value1\”:20,\”value2\”:$var1}”

    In this command how you imported the shell variable. It’s not working for me. I just created a bash script and stored the values in a variable. Whether I need to add more code in my bash script. I really need help on this

  17. Hey Steve!
    I can’t figure out this (probably simple) issue; I can subscribe to a topic on a locally running mosquitto broker using localhost/127.0.0.1 but I’m unable to connect using my private IP address.

    mosquitto_sub -h 192.168.0.163 -t ‘test’
    Error: Connection refused
    mosquitto_sub -h localhost -t ‘test’
    (success)

    I imagine this has something to do with the config file but I can’t pin down exactly what it is. Some help would be most appreciated 🙂 Thanks in advance!

    1. Hi
      Version 2 has security changes and only listens on the localhost you need to create a listener in the config file

      listener 1883

  18. Is it possible to resend topics received by the mosquitto broker running on a raspberry pi to resend in different format?

    For Domoticz topics: domoticz/out to domoticz/out/idx where idx ithe number from the body or message from the original topic

  19. Hi Steve,
    I have a groov Epic running Node-Red but I cannot get it to connect to my MQTT broker. I downloaded Eclipse MQTT v5/3.1.1 and installed it on my PC. I started the service. I tested it by opening a second window and doing the mosquitto_sub and mosquitto_pub routines. I created rules to allow port 1883 to receive and send through the firewall. Because it wouldn’t connect I installed wireshark on the broker PC and I can see the groov attempting to talk to the MQTT pc. Next I installed MQTT on another PC and attempted to send a message using the addition of -h 192.168.1.150. When I attempt to get the new PC to pub to the topic I have a sub running for on the MQTT I get the error “No connection could be made because the target machine actively refused it”. Wireshark also shows the attempt on port 1883 of the broker for this device. What am I missing?

    1. The message you are getting is usually caused by the broker not active on that port or that port is being blocked.

  20. Hi Steve,

    Thank you for this tutorial about Mosquitto_pub and Mosquitto_sub MQTT.

    I am trying to implement MQTT in C programming. Need to publish some values from sensor.

    Do you have any tutorials or guide on how to implement MQTT in C programming ?

  21. Hi Steve,

    mosquitto_sub doesn’t seem to work. It doesn’t show any message and keeps running till I press ctrl+c, doesn’t matter if a use the flag -C or not.

    I used the the second example (with debug flag) for publishing and it gave me the same details as the ones in image.

    C:\Program Files\mosquitto>mosquitto_pub -h {my-ip} -m “test message” -t house/bulb1 -d
    Client mosq-uzMlvnQQY5zT68jJ67 sending CONNECT
    Client mosq-uzMlvnQQY5zT68jJ67 received CONNACK (0)
    Client mosq-uzMlvnQQY5zT68jJ67 sending PUBLISH (d0, q0, r0, m1, ‘house/bulb1’, … (12 bytes))
    Client mosq-uzMlvnQQY5zT68jJ67 sending DISCONNECT

      1. mosquitto_sub -h {my-ip} -t house/#

        One update though. It seems to show the retained messages (only once) but not the other ones.

        1. That should work ok just use -d at the end. If it doesn’t can you send me a screenshot of the pub and sub. Do you have access to the broker console to see if it is sending the messages.
          Rgds
          Steve

          1. It’s working, thanks for the help!
            I was a bit confused and was writing both the _pub and _sub commands in the same console, so of course the not retained messages were not showing. Once I set _pub and _sub consoles separately, I could see the published messages.

  22. hi,
    while publishing i got error
    connection error: connection Refused: not authorised
    client test sending DISCONNECT

    command–mosquitto_pub -h localhost -u uname -p passcode -m “test” -t drove/tmt -p 1884st -p 1884 -r -d

  23. Hi
    I am trying to repeat the published message using the following command
    mosquitto_pub -h 10.0.0.2 -u “test” -P “test” -m “hi” –repeat 10
    It gives me error : “–repeat” unknown command
    How can I repeat my publish message?

    Thanks

  24. Hi Steve, Thank you very much for your tutorial. I’ve been trying to find ways to connect my edge devices(Raspberry Pis) to my EC2 sever with MQTT broker. However, as you mentioned in your tutorial the mosquitto_sub client would run indefinitely. If I want to process messages sent from the edge device via MQTT sub/pub system in real time and make requests to another sever, do you think it would be possible with moquitto_sub/mosquitto_pub?

    For example, I want to receive a message from my raspberry pi and everytime my EC2 sever get a new message, I want to make a API request to another website. Is this possible? and how should I do it? Thank you so much!!!

  25. Hi Steve,

    Is it possible to send a publish message with multiple topics and values for each topic?
    I need to send periodically some buffered values. For example, I want to send in the same publish message the topic test/item1 and value 1 and topic test/item2 and value 2.

  26. Thank you Steve for the help
    I am developing a communication system the uses a satellite channel. I am using the Mosquitto clients. On the subscriber side I collect the received messages in a file. To periodically read this file, I have to close de Subscriber client in order to read it and reset it (the code in my application will not allow me delete it or erase its contents while is in use by another application). To close the subscriber client I have the options of the -C switch or Ctrl C. The -C switch does not help as I have to control when the client is closed. And the Ctrl C is a manual option.
    My question is how do I close the subscriber client programmatically?

        1. Steve, the logger does a similar work I do with my code but more efficiently. The log info has to be processed and to do that It has to be read and deleted to start a new reading cycle. Can you reset the log files for each topic (by reset I mean to erase all content), using an external command or program?

          The idea is to monitor the log files periodically for data. If it has data, read the data for processing and erase it leaving the log file empty and ready for new data.

          I can not do that using the mosqutto sub client without closing if first.

          1. You can set the size of the log files and once closed you can delete them using an external program.
            It wouldn’t probably take much of a code change to have the files rotated every day.
            How are you reading the files. i.e python code etc
            Rgds
            Steve

  27. Hi steve. I’m a developer and I have some few doubts .
    1 ) Which programming language ( Python / Javascript ) is good for IoT Gateway .
    2) How to select database ( SQL / NoSQL ) for IoT project . As per my knowledge mostly we use NoSQL .
    Then when we use SQL .
    3) I have created a IoT gateway in Flask frame work . Is it good to use or else shall I develop it in Django
    framework or in Nodejs using javascript .
    4) How to know the limitations of a IoT gateway/ Platform . Like IoT gateway supports for 1000 devices .
    Can we predict it without connecting to that many devices .

    I will be waiting for your valuable response … Thanks in advance .

    1. Hi
      It all depends on the application and traffic expected. If you really do need speed then you need to go for c or Golang.
      Other than that I would choose the software that you are most comfortable with.
      I have a few basic traffic simulators that you can use for mock traffic.
      Sorry I can’t be more specific than that.
      Rgds
      Steve

  28. Excellent guidance! Thanks Steve!
    Just a remark. As a beginner (an non-native English) we spell every text line carefully and we are unaware of any required installs.
    I suggest to add that, as a precondition, the “Mosquitto Client package” needs to be installed for the example.
    On any Linux you install with the command: sudo apt-get install mosquitto-clients
    Thanks again! Was very helpfull!
    Bob

  29. Nice, helpfull.
    Using ssl I get these:

    mosquitto_sub -h mqt.meeiot.org -p 8883 -t test -u “93b9f” -P “xxx”

    error:140760FC:SSL routines:SSL23_GET_CLIENT_HELLO:unknown protocol

  30. Hi Steve, great tutorial, thanks. I’m using mosquitto on both, PC-Win7 and on my Pi. For both I use Domoticz interface. On my project I have an ESP8266 using ESPEASY with 3 sensors, one BME280 with Idx:4, second as ds18b20 for external temp as Idx:5, and last another ds18b20 for internal temperature with Idx:2. When I use the line command : mosquitto_sub -h localhost -t # or -t domoticz/in I get only the Idx:3 resulut as : {“idx”:3,”nvalue”:0,”svalue”:”20.23;50.81;0;1020.68;0″}
    What’s the syntax to get the others Idx ?
    Thanks.
    Vince.

    1. Sorry, in complement I check on ESPEASY then I put a 900 seconds delay, that probably why I don’t see immediately the result. I modify to 30 seconds time elapse and now I’m able to see that :
      domoticz/in {“idx”:4,”nvalue”:0,”svalue”:”12.00″}
      domoticz/in {“idx”:3,”nvalue”:0,”svalue”:”20.19;52.36;0;1020.82;0″}
      domoticz/out {
      “Battery” : 255,
      “RSSI” : 12,
      “description” : “Capteur BME280, Temp├®rature, hygrom├®trie, pression atmosph├®rique.”,
      “dtype” : “Temp + Humidity + Baro”,
      “id” : “82003”,
      “idx” : 3,
      “name” : “Multicapt”,
      “nvalue” : 0,
      “stype” : “THB1 – BTHR918, BTHGN129”,
      “svalue1” : “20.19”,
      “svalue2” : “52.36”,
      “svalue3” : “0”,
      “svalue4” : “1021”,
      “svalue5” : “0”,
      “unit” : 1
      }

      domoticz/out {
      “Battery” : 255,
      “RSSI” : 12,
      “description” : “Capteur BME280, Temp├®rature, hygrom├®trie, pression atmosph├®rique.”,
      “dtype” : “Temp + Humidity + Baro”,
      “id” : “82003”,
      “idx” : 3,
      “name” : “Multicapt”,
      “nvalue” : 0,
      “stype” : “THB1 – BTHR918, BTHGN129”,
      “svalue1” : “20.19”,
      “svalue2” : “52.36”,
      “svalue3” : “0”,
      “svalue4” : “1021”,
      “svalue5” : “0”,
      “unit” : 1
      }

      domoticz/out {
      “Battery” : 255,
      “RSSI” : 12,
      “description” : “Capteur BME280, Temp├®rature, hygrom├®trie, pression atmosph├®rique.”,
      “dtype” : “Temp + Humidity + Baro”,
      “id” : “82003”,
      “idx” : 3,
      “name” : “Multicapt”,
      “nvalue” : 0,
      “stype” : “THB1 – BTHR918, BTHGN129”,
      “svalue1” : “20.19”,
      “svalue2” : “52.36”,
      “svalue3” : “0”,
      “svalue4” : “1021”,
      “svalue5” : “0”,
      “unit” : 1
      }

      domoticz/out {
      “Battery” : 255,
      “RSSI” : 12,
      “description” : “Capteur BME280, Temp├®rature, hygrom├®trie, pression atmosph├®rique.”,
      “dtype” : “Temp + Humidity + Baro”,
      “id” : “82003”,
      “idx” : 3,
      “name” : “Multicapt”,
      “nvalue” : 0,
      “stype” : “THB1 – BTHR918, BTHGN129”,
      “svalue1” : “20.19”,
      “svalue2” : “52.36”,
      “svalue3” : “0”,
      “svalue4” : “1021”,
      “svalue5” : “0”,
      “unit” : 1
      }

      Why is only multiple time only the idx:3 repeat ?
      Is there a way to return only selected item as I.E sValue1, sValue2 and so on ?
      Thanks.
      Vince.

    1. Yes but you will need to write the app to do it.
      The receiver must receive the command and then do a system call to execute the command.
      Rgds
      Steve

  31. Excellent! Very much helpful.

    But I want to send and receive UTF-8 encoded string “∮ E⋅da = Q, n → ∞, ∑ f(i) = ∏ g(i), ∀x∈ℝ: ⌈x⌉ = −⌊−x⌋, α ∧ ¬β = ¬(¬α ∨ β)” using mosquitto_pub and mosquitto_sub applications. Is it possible? If so, Please share the details.

    1. Reading the docs then they support unicode but when I tried it the subscriber only displayed ascii.
      The tools are only really meant for testing and as such I only use them with simple strings.
      If you really do need this then make sure you use the latest versions as they have changed to support some of the features of MQTT version 5. I will do some tests and update the tutorial accordingly.
      This github question/response may be useful.
      https://github.com/eclipse/mosquitto/issues/593
      Rgds
      Steve

  32. Great info!
    I have Eclipse Mosquitto installed in a docker container on a Raspberry PI.
    It is working and showing MQTT data. I can use MQTT.fs from a windows 10 system and publish and subscribe.
    But, do not have access to any client tools.
    mosquitto_pub returns command not found. I want to use a python program to send cpu related data via MQTT but need this command. I have tried RPI-mosquitto and eclipse-mosquitto installed in containers with the same results. What am I doing wrong? Thanks

    1. On older windows installs the tools didn’t work and I forget why. They are included with he newer installs and work ok. You could download my install files for windows put them in a folder on the docker image called mos and then change to that directory and run them. There is no need to do any install.
      you can find the files by following this link.
      http://www.steves-internet-guide.com/install-mosquitto-broker/
      Let me know if it works ok
      rgds
      steve

  33. HI Steve,
    Thanks for the Great tutorial. i am able to send the messages to the topics.
    Do you have any example use case programs to send data.

  34. Hello steve
    great tutorial
    I am getting this error
    can you tell me what i can do
    error: No connection could be made because the target machine actively refused it.

  35. Hello Steve, thanks for this nice documentation. I ham having some problem with using mosquitto_pub with SSLCertificate. On the client side, when i use:
    mosquitto_pub -h 127.0.0.1 -t test -m “message” -d –cafile certs\ca.crt -p 8883 –insecure
    it shows the following error:
    Client mosqpub|13588-nb2166 sending CONNECT
    Error: A TLS error occurred.
    On the Broker side, it shows the following error:
    1534923031: New connection from 127.0.0.1 on port 8883.
    1534923031: Socket error on client , disconnecting.
    I have already tested the Broker with MQTTfx and there it works fine with certificate. Could you help me out please ?

      1. Yes that is true. it is the same path also added in mosquitto conf in the line cafile.
        and it also shows the following error on the broker side.
        1534933587: New connection from 127.0.0.1 on port 8883.
        1534933587: OpenSSL Error: error:14094418:SSL routines:ssl3_read_bytes:tlsv1 alert unknown ca
        1534933587: OpenSSL Error: error:140940E5:SSL routines:ssl3_read_bytes:ssl handshake failure
        1534933587: Socket error on client , disconnecting.

        Is it a problem to use a selfed signed certificate? How to solve this problem?

      2. Hello Steve, I found the issue. It was showing the error that the CA is unknown as i had put the same information in both the information in server and ca crt files. For other users, please do not forget to read the yellow note on this webpage or else you will end up like me. 😉
        http://www.steves-internet-guide.com/mosquitto-tls/
        In short if you get this error from OpenSSL, it means the certificates are not correct:
        1534938680: New connection from 127.0.0.1 on port 8883.
        1534938680: OpenSSL Error: error:14094418:SSL routines:ssl3_read_bytes:tlsv1 alert unknown ca
        1534938680: OpenSSL Error: error:140940E5:SSL routines:ssl3_read_bytes:ssl handshake failure
        1534938680: Socket error on client , disconnecting.
        Now it mosquitto_pub as well as libmosquitto are working correctly. THank you again.

Leave a Reply

Your email address will not be published. Required fields are marked *