Eclipse Paho MQTT C++ Client Library

Overview

Eclipse Paho MQTT C++ Client Library

Build Status

This repository contains the source code for the Eclipse Paho MQTT C++ client library on memory-managed operating systems such as Linux/Posix and Windows.

This code builds a library which enables C++11 applications to connect to an MQTT broker, publish messages to the broker, and to subscribe to topics and receive published messages.

The library has the following features:

  • Support for MQTT v3.1, v3.1.1, and v5.
  • Network Transports:
    • Standard TCP
    • Secure sockets with SSL/TLS
    • WebSockets
      • Secure and insecure
      • Proxy support
  • Message persistence
    • User configurable
    • Built-in File persistence
    • User-defined key/value persistence easy to implement
  • Automatic Reconnect
  • Offline Buffering
  • High Availability
  • Blocking and non-blocking API's
  • Modern C++ interface (C++11 and better)

This code requires the Paho C library by Ian Craggs, et al., specifically version 1.3.8 or possibly later.

Latest News

To keep up with the latest announcements for this project, or to ask questions:

Twitter: @eclipsepaho and @fmpagliughi

EMail: Eclipse Paho Mailing List

Mattermost: Eclipse Mattermost Paho Channel

Unreleased features in this branch

  • Added Session Expiry Interval to v5 chat sample
  • Minor tweaks to prepare for C++20
  • Minor cleanup of the tests #317 String constructor using just len instead of end iterator. #337 Copy and move constructors/assignment of ssl_options not handling CA path.

What's new in Version 1.2.0

This release brings in some missing MQTT v5 features, support for websocket headers and proxies, ALPN protocol lists, adds the builder pattern for options, and fixes a number of bugs in both the C++ library and the underlying C lib.

Requires Paho C v1.3.8

  • Missing MQTT v5 features:
    • Ability to add properties to Subscribe and Unsubscribe packets (i.e. subscription identifiers)
    • "Disconnected" callback gives reason code and properties for server disconnect
  • New create_options that can be used to construct a client with new features:
    • Send while disconnected before the 1st successful connection
    • Output buffer can delete oldest messages when full
    • Can choose to clear the persistence store on startup
    • Select whether to persist QoS 0 messages
  • Started classes to create options using the Builder Pattern, with the create_options_builder, connect_options_builder, message_ptr_builder, etc.
  • User-defined websocket HTTP headers.
  • HTTP/S proxy support
  • Added ALPN protocol support to SSL/TLS options
  • SSL/TLS error and PSK callback support
  • Update connection callback support (change credentials when using auto-reconnect)
  • Updates to the sample apps:
    • Overall cleanup with better consistency
    • Example of using websockets and a proxy
    • User-based file persistence with simple encoding/encryption
    • Sharing a client between multiple threads
  • Converted the unit tests to use Catch2
  • All library exceptions are now properly derived from the mqtt::exception base class.
  • [#231] Added on_disconnected callback to handle receipt of disconnect packet from server.
  • [#211, #223, #235] Removed use of Log() function from the Paho C library.
  • [#227] Fixed race condition in thread-safe queue
  • [#224] & [#255] Subscribing to MQTT v3 broker with array of one topic causes segfault.
  • [#282] Ability to build Debian/Ubuntu package
  • [#300] Calling reconnect() was hanging forever, even when successful. In addition several of the synchronous client calls were hanging forever on failure. They now properly throw a timeout_error exception.
  • Several memory issues and bug fixes from updated Paho C library support.

Catch2 Unit Tests

Unit tests were converted to use Catch2 for the test framework.

Catch2 can be found here: Catch2

Contributing

Contributions to this project are gladly welcomed and appreciated Before submitting a Pull Request, please keep three things in mind:

  • This is an official Eclipse project, so it is required that all contributors sign an Eclipse Contributor Agreement (ECA)
  • Please submit all Pull Requests against the develop branch (not master).
  • Please sign all commits.

For full details, see CONTRIBUTING.md.

Building from source

CMake is a cross-platform build system suitable for Unix and non-Unix platforms such as Microsoft Windows. It is now the only supported build system.

The Paho C++ library requires the Paho C library, v1.3.8 or greater, to be built and installed first. More information below.

CMake allows for options to direct the build. The following are specific to Paho C++:

Variable Default Value Description
PAHO_BUILD_SHARED TRUE (Linux), FALSE (Win32) Whether to build the shared library
PAHO_BUILD_STATIC FALSE (Linux), TRUE (Win32) Whether to build the static library
PAHO_BUILD_DOCUMENTATION FALSE Create and install the HTML based API documentation (requires Doxygen)
PAHO_BUILD_SAMPLES FALSE Build sample programs
PAHO_BUILD_TESTS FALSE Build the unit tests. (This requires Catch2)
PAHO_WITH_SSL TRUE (Linux), FALSE (Win32) Flag that defines whether to build ssl-enabled binaries too
PAHO_BUILD_DEB_PACKAGE FALSE Flag that configures cpack to build a Debian/Ubuntu package

In addition, the C++ build might commonly use CMAKE_PREFIX_PATH to help the build system find the location of the Paho C library.

Unix and Linux

On *nix systems CMake creates Makefiles.

The build process currently supports a number of Unix and Linux flavors. The build process requires the following tools:

  • CMake v3.5 or newer
  • GCC v4.8 or newer or Clang v3.9 or newer
  • GNU Make

On Debian based systems this would mean that the following packages have to be installed:

$ sudo apt-get install build-essential gcc make cmake cmake-gui cmake-curses-gui

If you will be using secure sockets (and you probably should):

$ sudo apt-get install libssl-dev 

Building the documentation requires doxygen and optionally graphviz to be installed:

$ sudo apt-get install doxygen graphviz

Unit tests are being built using Catch2.

Catch2 can be found here: Catch2. You must download and install Catch2 to build and run the unit tests locally.

Building the Paho C library

Before building the C++ library, first, build and install the Paho C library, if not already present. Note, this version of the C++ library requires Paho C v1.3.8 or greater.

$ git clone https://github.com/eclipse/paho.mqtt.c.git
$ cd paho.mqtt.c
$ git checkout v1.3.8

$ cmake -Bbuild -H. -DPAHO_ENABLE_TESTING=OFF -DPAHO_BUILD_STATIC=ON \
    -DPAHO_WITH_SSL=ON -DPAHO_HIGH_PERFORMANCE=ON
$ sudo cmake --build build/ --target install
$ sudo ldconfig

This builds with SSL/TLS enabled. If that is not desired, omit the -DPAHO_WITH_SSL=ON.

It also uses the "high performace" option of the C library to disable more extensive internal memory checks. Remove the PAHO_HIGH_PERFORMANCE option (i.e. turn it off) to debug memory issues, but for most production systems, leave it on for better performance.

To install the library to a non-standard location, use the CMAKE_INSTALL_PREFIX to specify a location. For example, to install into under the build directory, perhaps for local testing, do this:

$ cmake -Bbuild -H. -DPAHO_ENABLE_TESTING=OFF -DPAHO_BUILD_STATIC=ON \
    -DPAHO_WITH_SSL=ON -DPAHO_HIGH_PERFORMANCE=ON \
    -DCMAKE_INSTALL_PREFIX=./build/_install

Building the Paho C++ library

An example CMake build session might look like this:

$ git clone https://github.com/eclipse/paho.mqtt.cpp
$ cd paho.mqtt.cpp

$ cmake -Bbuild -H. -DPAHO_BUILD_STATIC=ON \
    -DPAHO_BUILD_DOCUMENTATION=TRUE -DPAHO_BUILD_SAMPLES=TRUE
$ sudo cmake --build build/ --target install
$ sudo ldconfig

If you did not install Paho C library to a default system location or you want to build against a different version, use the CMAKE_PREFIX_PATH to specify its install location. Perhaps something like this:

$ cmake -Bbuild -H. -DPAHO_BUILD_DOCUMENTATION=ON -DPAHO_BUILD_SAMPLES=ON \
    -DPAHO_BUILD_STATIC=ON \
    -DCMAKE_PREFIX_PATH=$HOME/mqtt/paho.mqtt.c/build/_install

To use another compiler, either the CXX environment variable can be specified in the configuration step:

$ CXX=clang++ cmake ..

or the CMAKE_CXX_COMPILER flag can be used:

$ cmake -DCMAKE_CXX_COMPILER=clang++

Building a Debian/Ubuntu package

$ cmake -Bbuild -H. -DPAHO_WITH_SSL=ON -DPAHO_ENABLE_TESTING=OFF -DPAHO_BUILD_DEB_PACKAGE=ON
$ cmake --build build
$ (cd build && cpack)

will generate a .deb file.

Windows

On Windows systems CMake creates Visual Studio project files.

The build process currently supports a number Windows versions. The build process requires the following tools:

  • CMake GUI v3.5 or newer
  • Visual Studio 2015 or newer

First install and open the cmake-gui application. This tutorial is based on cmake-gui 3.5.2.

Second, select the path to the Paho MQTT C library (CMAKE_PREFIX_PATH) if not installed in a standard path. Remember that the Paho MQTT C must be installed on the system. Next, choose if it is supposed to build the documentation (PAHO_BUILD_DOCUMENTATION) and/or the sample applications (PAHO_BUILD_SAMPLES).

Once the configuration is done, click on the Configure button, select the version of the Visual Studio, and then click on Generate button.

At the end of this process you have a Visual Studio solution.

Alternately, the libraries can be completely built at an MSBuild Command Prompt. Download the Paho C and C++ library sources, then open a command window and first compile the Paho C library:

> cd paho.mqtt.c
> cmake -Bbuild -H. -DCMAKE_INSTALL_PREFIX=C:\mqtt\paho-c
> cmake --build build/ --target install

Then build the C++ library:

> cd ..\paho.mqtt.cpp
> cmake -Bbuild -H. -DCMAKE_INSTALL_PREFIX=C:\mqtt\paho-cpp -DPAHO_BUILD_SAMPLES=ON -DPAHO_WITH_SSL=OFF -DCMAKE_PREFIX_PATH=C:\mqtt\paho-c
> cmake --build build/ --target install

This builds and installs both libraries to a non-standard location under C:\mqtt. Modify this location as desired or use the default location, but either way, the C++ library will most likely need to be told where the C library was built using CMAKE_PREFIX_PATH.

It seems quite odd, but even on a 64-bit system using a 64-bit compiler, MSVC seems to default to a 32-bit build target.

The 64-bit target can be selected using tge CMake generator switch, -G, at configuration time. The full version must be provided. For Visual Studio 2015 which is v14 do this to first build the Paho C library:

> cmake -G "Visual Studio 14 Win64" -Bbuild -H. -DCMAKE_INSTALL_PREFIX=C:\mqtt\paho-c
...

Then use it to build the C++ library:

> cmake -G "Visual Studio 14 Win64" -Bbuild -H. -DCMAKE_INSTALL_PREFIX=C:\mqtt\paho-cpp -DPAHO_WITH_SSL=OFF -DCMAKE_PREFIX_PATH=C:\mqtt\paho-c
...

Note that it is very important that you use the same generator (target) to build BOTH libraries, otherwise you will get lots of linker errors when you try to build the C++ library.

Supported Network Protocols

The library supports connecting to an MQTT server/broker using TCP, SSL/TLS, and websockets (secure and unsecure). This is chosen by the URI supplied to the connect() call. It can be specified as:

: " - TCP (unsecure) "ssl:// : " - SSL/TLS "ws:// : " - Unsecure websockets "wss:// : " - Secure websockets ">
"tcp://
           
            :
            
             "  - TCP (unsecure)
"ssl://
             
              :
              
               "  - SSL/TLS
"ws://
               
                :
                
                 " - Unsecure websockets "wss://
                 
                  :
                  
                   " - Secure websockets 
                  
                 
                
               
              
             
            
           

Note that to use "ssl://" or "wss://" you must compile the library with OpenSSL, and you must supply a set of ssl_options with the connect_options.

Example

Sample applications can be found in the source repository at src/samples: https://github.com/eclipse/paho.mqtt.cpp/tree/master/src/samples

This is a partial example of what a typical example might look like:

int main(int argc, char* argv[])
{
    sample_mem_persistence persist;
    mqtt::client cli(ADDRESS, CLIENT_ID, &persist);

    callback cb;
    cli.set_callback(cb);

    auto connOpts = mqtt::connect_options_builder() 
        .keep_alive_interval(20);
        .clean_session()
        .finalize();

    try {
        cli.connect(connOpts);

        // First use a message pointer.

        mqtt::message_ptr pubmsg = mqtt::make_message(PAYLOAD1);
        pubmsg->set_qos(QOS);
        cli.publish(TOPIC, pubmsg);

        // Now try with itemized publish.

        cli.publish(TOPIC, PAYLOAD2, strlen(PAYLOAD2)+1, 0, false);

        // Disconnect
        
        cli.disconnect();
    }
    catch (const mqtt::persistence_exception& exc) {
        cerr << "Persistence Error: " << exc.what() << " ["
            << exc.get_reason_code() << "]" << endl;
        return 1;
    }
    catch (const mqtt::exception& exc) {
        cerr << "Error: " << exc.what() << " ["
            << exc.get_reason_code() << "]" << endl;
        return 1;
    }

    return 0;
}

The original API organization and documentation were adapted from:

The Paho Java library by Dave Locke et al. Copyright (c) 2012, IBM Corp

All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v10.html


This code requires:

The Paho C library by Ian Craggs Copyright (c) 2013-2018, IBM Corp.

All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution.

The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php.

Comments
  • async_subscribe.cpp example receives twice the on_success() notification for connection

    async_subscribe.cpp example receives twice the on_success() notification for connection

    I configured the example to connect to the test server "tcp://test.mosquitto.org:1883" This is the output:

    $ ./src/samples/async_subscribe Connecting to the MQTT server... Connection success

    Subscribing to topic 'hello' for client async_subcribe_cpp using QoS1

    Press Q to quit

    Connection success

    Subscribing to topic 'hello' for client async_subcribe_cpp using QoS1

    Press Q to quit

    Subscription success for token: [1] token topic: 'hello', ...

    Message arrived topic: 'hello' payload: 'hi'

    Subscription success for token: [2] token topic: 'hello', ...

    Message arrived topic: 'hello' payload: 'hi'

    Message arrived topic: 'hello' payload: 'snsfgsnb'

    Q

    bug 
    opened by whizmo 18
  • [ ERROR ] [ ERROR ] MQTT error [-8]: Bad structure

    [ ERROR ] [ ERROR ] MQTT error [-8]: Bad structure

    Hello, I have built a project before using this with no issues.

    However, now I am getting this error:

    [ ERROR ] [ ERROR ] MQTT error [-8]: Bad structure
    

    When calling this:

            std::string address = "tcp://192.168.1.51:1883";
            std::string client = "some-client";
    
            mqtt::async_client cli(address, client);
    

    I have absolutely no idea why this is failing like this. I have followed the instructions exactly as described in the readme for building both paho.mqtt.c and paho.mqtt.cpp.

    Any ideas on why this might be happening?

    opened by AndBobsYourUncle 17
  • Possible memory leak

    Possible memory leak

    When monitoring some processes of mine, I recognized a slowly inreasing memory usage over time.
    So after quite some time of debugging, it looks like there is some sort of memory leak in the library.
    More specifically, memory increases only when I subscribe to a topic and messages are incoming. In the PAHO C lib I dont see this leak.

    I added my test code, so you can try out. Let it run for a minute and memory usage should be up.

    The dummy_callback_listener does nothing with the message itself, just an empty callback.

    getMemoryUsage gets its data from ifstream stat_stream("/proc/self/stat",ios_base::in);

    Hope you can help me out here.

    PAHO CPP VERSION "1.0.1" PAHO C VERSION "1.3.0"
    Ubuntu 18.04

       mqtt::connect_options connectOptions;
    
       std::unique_ptr<mqtt::async_client>asyncClient = std::make_unique<mqtt::async_client>( mqtt::SERVER_ADDRESS, "MemoryRawClientTests" );
       auto conntok = asyncClient->connect( connectOptions );
       conntok->wait();
       asyncClient->start_consuming();
    
       dummy_callback_listener callbackListener;
       asyncClient->set_callback(callbackListener);
    
       dummy_action_listener listener;
       asyncClient->subscribe(mqtt::SERVER_TOPIC, 0, nullptr, listener);
    
       std::string payload = "SimpleMessageCallbackTestSimpleMessageCallbackTestSimpleMessageCallbackTestSimpleMessageCallbackTestSimpleMessageCallbackTest";
       mqtt::message_ptr message = mqtt::make_message(mqtt::SERVER_TOPIC, payload.c_str(), payload.size());
    
       while (true)
       {
          asyncClient->publish(message);
          log_info("mem usage: {}", getMemoryUsageString() );
          std::this_thread::sleep_for(10ms);
       }
    
    opened by maxlein 15
  • [Suggestion] Blocking method for receiving messages

    [Suggestion] Blocking method for receiving messages

    I'm using the synchronous client, but I still need to set a callback class in order to handle the incoming messages in an asynchronous way. I think it would be easier if the own client worked as a socket, buffering all the incoming messages. The client class would have a "receive" method or so, which pops the next message from the queue. If it's empty, it could block for some timeout period that would be passed as an argument.

    enhancement 
    opened by andre-vm 15
  • paho.mqtt.cpp - version with SSL / TLS support?

    paho.mqtt.cpp - version with SSL / TLS support?

    Hi

    Where can i get it? Currently we use the non-secure version on: https://github.com/eclipse/paho.mqtt.cpp.git

    But now we need the version that supports SSL / TLS...

    Thank you for your feedbacks...

    With kind regards, Jan

    opened by jayjupdhig 12
  • TLS issue cpp on macOS

    TLS issue cpp on macOS

    Hi guys,

    I am trying to connect to my mosquitto server using c++ on my mac and I am getting this error :

    123145416470528:error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure:s3_pkt.c:1500:SSL alert number 40
    MQTT error [-1]: TCP/TLS connect failure
    

    I am using the same certificates I am using on my raspberry pi which is currently running and publishing data.

    This is the code I use right now. I scrapped it from tests and samples.

     try{
            mqtt::client client(ADDRESS, "10");
            mqtt::connect_options connOpts;
            mqtt::ssl_options sslOptions;
            sslOptions.set_trust_store("/Users/jefflabonte/Documents/Development/Projects/MyProject/certificates/device001_certs/mycert.pem");
    //        sslOptions.set_key_store("/Users/jefflabonte/Documents/Development/Projects/MyProject/certificates/device001_certs/device001.crt");
            connOpts.set_ssl(sslOptions);
            connOpts.set_mqtt_version(MQTTVERSION_3_1_1);
            connOpts.set_keep_alive_interval(20);
            connOpts.set_clean_session(true);
    
            client.connect(connOpts);
    
        }catch(mqtt::exception ex){
            std::cerr << ex.to_string() << std::endl;
    
        }
    

    Any idea on what I did wrong?

    opened by JeffLabonte 12
  • Support for CMake v2.8

    Support for CMake v2.8

    CMake for the C++ library is asking for version 3.1. Is there anything significant that would need to be done to support slightly older versions of CMake, perhaps back to version 2.8?

    This is the version that comes with Ubuntu 14.04 LTS, Linux Mint 17 LTS, and (I believe) the latest Raspberry Pi Raspbian, Nvidia TX1, and a number of other embedded Linux boards. These could use autotools or Make, but it would be nice to have CMake work for them as it is likely to became the default build standard.

    [ubuntu-14.04] $ cmake ..
    CMake Error at CMakeLists.txt:20 (cmake_minimum_required):
      CMake 3.1 or higher is required.  You are running version 2.8.12.2
    
    -- Configuring incomplete, errors occurred!
    

    @guilhermeferreira

    enhancement 
    opened by fpagliughi 12
  • System cannot find -lmqttv3a & -lmqttpp

    System cannot find -lmqttv3a & -lmqttpp

    Hi,

    I encountered a problem when compiling the sample c++ code. It seems lack of libraries files. Is it because there's no "make install" option to add those libraries into system path?

    I also tried paho.mqtt.c, that compile has no issue happen.

    jason2015@ubuntu:~/mqtt/paho.mqtt.cpp/src/samples$ make sync_publish g++ -I.. -I/home/fmp/static/opensrc/mqtt/paho/org.eclipse.paho.mqtt.c/src -D_NDEBUG -Wall -std=c++0x -O2 -o sync_publish sync_publish.cpp -L../lib -L/home/fmp/static/opensrc/mqtt/paho/org.eclipse.paho.mqtt.c/src/linux_ia64 -lmqttpp -lmqttv3a /usr/bin/ld: cannot find -lmqttv3a collect2: error: ld returned 1 exit status make: *** [sync_publish] Error 1

    Best Regards!

    opened by Jason-Gew 12
  • Modernize the build system

    Modernize the build system

    Modernize the CMake build system, including the generation and installation of a CMake package configuration file. This will make it easier for CMake-enabled projects to use paho.mqtt.cpp: they'll just have to call find_package(PahoMqttCpp) and then have their targets link against PahoMqttCpp::paho-mqttpp3.

    Also, remove the other build systems because maintaining multiple build systems is painful.

    opened by dawagner 11
  • Instantiate client pointer

    Instantiate client pointer

    Hello, I've been using the MQTT c++ library with success but I do not understand how the mqtt::client_ptr works.

    I see that it's a shared pointer, but how do I instantiate it? the constructor is deleted, and std::make_sharedmqtt::client() doesn't work as well.

    opened by ptrsr 11
  • does the v1.1 work with  paho.mqtt.c 1.3.5 ?

    does the v1.1 work with paho.mqtt.c 1.3.5 ?

    I can not find any info

    is it recommended to stay with paho.mqtt.c 1.3.1 ? there have been quite some changes, and I guess fixes and improvements since this version in paho.mqtt.c

    opened by a4z 10
  • When token completes before action callback is set, callback is never called

    When token completes before action callback is set, callback is never called

    Let's say you have a scenario like this:

    async_client client{ MY_PARAMETERS };
    client.disconnect(MY_TIMEOUT)->set_action_callback(MY_LISTENER);
    

    In this case it is possible that the disconnect finishes before the listener is set internally. When that happens the listener is never called anymore.

    Would it be acceptable from your side to, IF the token was already completed, call the listener directly when it is set? From a user side it is hard to do this thread safe, but you have the locks in place to allow it. A PR will come tomorrow and then you can decide!

    opened by Stannieman 0
  • Why don't we import paho mqtt c targets directly?

    Why don't we import paho mqtt c targets directly?

    Currently, the CMake finds paho.mqtt.c with a shim FindPahoMqttC.cmake file. This calls find_library on the desired library name, and manually calls find_path on MQTTAsync.h.

    Why do we go through this effort when paho.mqtt.c already exports a config file (eclipse-paho-mqtt-cConfig.cmake) that exports its targets?

    Basically my thought is that we should change find_package(PahoMqttC) to find_package(eclipse-paho-mqtt-c).

    If there is a technical/historical reason for this that I am missing, please let me know. I'm new to the project.

    opened by Aposhian 0
  • When ConnectLost is invoked

    When ConnectLost is invoked

    Hello, I use this library to set the heartbeat interval to 2 minutes. Why is the ConnectLost callback activated quickly when the network is unavailable? Sometimes it takes more than 2 minutes to activate.

    opened by 2751466366 0
  • Wrong return value of mqtt::client::try_consume_message_for() when it disconnects

    Wrong return value of mqtt::client::try_consume_message_for() when it disconnects

    Hello,

    I use the mqtt::client to connect to an MQTT broker and then, in a different thread, I call regularly the function client.try_consume_message_for(&message_ptr, std::chrono::seconds{1}). If the function returns false, I attempt a reconnect and if it returns true, I handle the message. Now if the broker disconnect remotely and the client is currently within the call try_consume_message_for, the call returns with the value true and with message_ptr set to nullptr. I think, the call should return with false if the message_ptr value is not set (or set to nullptr). The next call(s) to try_consume_message_for returns false as expected. Rough example:

    class MyClass {
       void MyClass(mqtt::connect_options options) {
          client_ = std::make_unique<mqtt::client>("host", "client_id");
          client_->start_consuming();
    
          client_->connect(options);
          thread_ = std::thread {
             mqtt::const_message_ptr mqtt_message;
             while (true) {
                if (!client_->try_consume_message_for(&mqtt_message, std::chrono::seconds{1})) {
                     print("disconnected... attempt reconnect");
                     // add code to reconnect
                     continue;
                 }
                 
                  auto payload = mqtt_message->get_payload(); // this crashes on disconnect since try_consume_message_for returned true
             }
          };
       }
    
       std::unique_ptr<mqtt::client> client_;
       std::thread thread_;
    }
    
    opened by Naslow 0
  • Cannot compile under windows 11

    Cannot compile under windows 11

    I'm trying to compile following the instructions in the readme but it fails with Could NOT find PahoMqttC (missing: PAHO_MQTT_C_LIBRARIES):

    C:\Users\Matteo\Documents\paho.mqtt.cpp>cmake -Bbuild -H. -DCMAKE_INSTALL_PREFIX=C:\mqtt\paho-cpp -DPAHO_BUILD_SAMPLES=ON -DPAHO_WITH_SSL=OFF -DCMAKE_PREFIX_PATH=C:\mqtt\paho-c
    -- Building for: Visual Studio 17 2022
    -- The CXX compiler identification is MSVC 19.33.31630.0
    -- Detecting CXX compiler ABI info
    -- Detecting CXX compiler ABI info - done
    -- Check for working CXX compiler: C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.33.31629/bin/Hostx64/x64/cl.exe - skipped
    -- Detecting CXX compile features
    -- Detecting CXX compile features - done
    CMake Error at C:/Program Files/CMake/share/cmake-3.24/Modules/FindPackageHandleStandardArgs.cmake:230 (message):
      Could NOT find PahoMqttC (missing: PAHO_MQTT_C_LIBRARIES)
    Call Stack (most recent call first):
      C:/Program Files/CMake/share/cmake-3.24/Modules/FindPackageHandleStandardArgs.cmake:594 (_FPHSA_FAILURE_MESSAGE)
      cmake/FindPahoMqttC.cmake:33 (FIND_PACKAGE_HANDLE_STANDARD_ARGS)
      src/CMakeLists.txt:26 (find_package)
    
    
    -- Configuring incomplete, errors occurred!
    See also "C:/Users/Matteo/Documents/paho.mqtt.cpp/build/CMakeFiles/CMakeOutput.log".
    

    Checking the CMakeList.txt file in src it is possible to see that the find_package instruction search for what seems to be the wrong package name: https://github.com/eclipse/paho.mqtt.cpp/blob/master/src/CMakeLists.txt#L26 :

    find_package(PahoMqttC REQUIRED)
    

    While, according to the README of the C library you should use a different package name https://github.com/eclipse/paho.mqtt.c#building-your-application-with-cmake :

    find_package(eclipse-paho-mqtt-c REQUIRED)
    

    And a test build with this change leads to a different error:

    C:\Users\Matteo\Documents\paho.mqtt.cpp>cmake -Bbuild -H. -DCMAKE_INSTALL_PREFIX=C:\mqtt\paho-cpp -DPAHO_BUILD_SAMPLES=ON -DPAHO_WITH_SSL=OFF -DCMAKE_PREFIX_PATH=C:\mqtt\paho-c
    -- Performing Test CMAKE_HAVE_LIBC_PTHREAD
    -- Performing Test CMAKE_HAVE_LIBC_PTHREAD - Failed
    -- Check if compiler accepts -pthread
    -- Check if compiler accepts -pthread - no
    -- Looking for pthread_create in pthreads
    -- Looking for pthread_create in pthreads - not found
    -- Looking for pthread_create in pthread
    -- Looking for pthread_create in pthread - not found
    -- Found Threads: TRUE
    -- Configuring done
    CMake Error at src/CMakeLists.txt:126 (target_link_libraries):
      Target "paho-mqttpp3-static" links to:
    
        PahoMqttC::PahoMqttC
    
      but the target was not found.  Possible reasons include:
    
        * There is a typo in the target name.
        * A find_package call is missing for an IMPORTED target.
        * An ALIAS target is missing.
    
    
    
    -- Generating done
    CMake Generate step failed.  Build files cannot be regenerated correctly.
    

    Updating the target_link_libraries according to the documentation of the C library (line 126):

        ## add dependencies to the shared library
        target_link_libraries(paho-mqttpp3-static
            PRIVATE ${LIBS_SYSTEM}
            PUBLIC eclipse-paho-mqtt-c::paho-mqtt3a Threads::Threads)
    

    CMake can create the build files correctly:

    C:\Users\Matteo\Documents\paho.mqtt.cpp>cmake -Bbuild -H. -DCMAKE_INSTALL_PREFIX=C:\mqtt\paho-cpp -DPAHO_BUILD_SAMPLES=ON -DPAHO_WITH_SSL=OFF -DCMAKE_PREFIX_PATH=C:\mqtt\paho-c
    -- Building for: Visual Studio 17 2022
    -- The CXX compiler identification is MSVC 19.33.31630.0
    -- Detecting CXX compiler ABI info
    -- Detecting CXX compiler ABI info - done
    -- Check for working CXX compiler: C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.33.31629/bin/Hostx64/x64/cl.exe - skipped
    -- Detecting CXX compile features
    -- Detecting CXX compile features - done
    -- Performing Test CMAKE_HAVE_LIBC_PTHREAD
    -- Performing Test CMAKE_HAVE_LIBC_PTHREAD - Failed
    -- Check if compiler accepts -pthread
    -- Check if compiler accepts -pthread - no
    -- Looking for pthread_create in pthreads
    -- Looking for pthread_create in pthreads - not found
    -- Looking for pthread_create in pthread
    -- Looking for pthread_create in pthread - not found
    -- Found Threads: TRUE
    -- Configuring done
    -- Generating done
    -- Build files have been written to: C:/Users/Matteo/Documents/paho.mqtt.cpp/build
    

    But the system cannot actually build:

    C:\Users\Matteo\Documents\paho.mqtt.cpp>cmake --build build/ --target install
    MSBuild version 17.3.1+2badb37d1 for .NET Framework
      Building Custom Rule C:/Users/Matteo/Documents/paho.mqtt.cpp/src/CMakeLists.txt
      async_client.cpp
    C:\Users\Matteo\Documents\paho.mqtt.cpp\src\mqtt/async_client.h(28,10): fatal  error C1083: Cannot open include file: 'MQTTAsync.h': No such file or directory [C:\Users\Matteo\Doc
    uments\paho.mqtt.cpp\build\src\paho-cpp-objs.vcxproj]
      client.cpp
    C:\Users\Matteo\Documents\paho.mqtt.cpp\src\mqtt/async_client.h(28,10): fatal  error C1083: Cannot open include file: 'MQTTAsync.h': No such file or directory [C:\Users\Matteo\Doc
    uments\paho.mqtt.cpp\build\src\paho-cpp-objs.vcxproj]
      connect_options.cpp
    C:\Users\Matteo\Documents\paho.mqtt.cpp\src\mqtt/connect_options.h(27,10): fatal  error C1083: Cannot open include file: 'MQTTAsync.h': No such file or directory [C:\Users\Matteo\
    Documents\paho.mqtt.cpp\build\src\paho-cpp-objs.vcxproj]
      create_options.cpp
    C:\Users\Matteo\Documents\paho.mqtt.cpp\src\mqtt/create_options.h(27,10): fatal  error C1083: Cannot open include file: 'MQTTAsync.h': No such file or directory [C:\Users\Matteo\D
    ocuments\paho.mqtt.cpp\build\src\paho-cpp-objs.vcxproj]
      disconnect_options.cpp
    C:\Users\Matteo\Documents\paho.mqtt.cpp\src\mqtt/disconnect_options.h(26,10): fatal  error C1083: Cannot open include file: 'MQTTAsync.h': No such file or directory [C:\Users\Matt
    eo\Documents\paho.mqtt.cpp\build\src\paho-cpp-objs.vcxproj]
      iclient_persistence.cpp
    C:\Users\Matteo\Documents\paho.mqtt.cpp\src\mqtt/iclient_persistence.h(27,10): fatal  error C1083: Cannot open include file: 'MQTTAsync.h': No such file or directory [C:\Users\Mat
    teo\Documents\paho.mqtt.cpp\build\src\paho-cpp-objs.vcxproj]
      message.cpp
    C:\Users\Matteo\Documents\paho.mqtt.cpp\src\mqtt/message.h(28,10): fatal  error C1083: Cannot open include file: 'MQTTAsync.h': No such file or directory [C:\Users\Matteo\Document
    s\paho.mqtt.cpp\build\src\paho-cpp-objs.vcxproj]
      properties.cpp
    C:\Users\Matteo\Documents\paho.mqtt.cpp\src\mqtt/properties.h(28,11): fatal  error C1083: Cannot open include file: 'MQTTProperties.h': No such file or directory [C:\Users\Matteo\
    Documents\paho.mqtt.cpp\build\src\paho-cpp-objs.vcxproj]
      response_options.cpp
    C:\Users\Matteo\Documents\paho.mqtt.cpp\src\mqtt/response_options.h(10,10): fatal  error C1083: Cannot open include file: 'MQTTAsync.h': No such file or directory [C:\Users\Matteo
    \Documents\paho.mqtt.cpp\build\src\paho-cpp-objs.vcxproj]
      ssl_options.cpp
    C:\Users\Matteo\Documents\paho.mqtt.cpp\src\mqtt/ssl_options.h(30,10): fatal  error C1083: Cannot open include file: 'MQTTAsync.h': No such file or directory [C:\Users\Matteo\Docu
    ments\paho.mqtt.cpp\build\src\paho-cpp-objs.vcxproj]
      string_collection.cpp
    C:\Users\Matteo\Documents\paho.mqtt.cpp\src\mqtt/string_collection.h(27,10): fatal  error C1083: Cannot open include file: 'MQTTAsync.h': No such file or directory [C:\Users\Matte
    o\Documents\paho.mqtt.cpp\build\src\paho-cpp-objs.vcxproj]
      subscribe_options.cpp
    C:\Users\Matteo\Documents\paho.mqtt.cpp\src\mqtt/subscribe_options.h(27,10): fatal  error C1083: Cannot open include file: 'MQTTAsync.h': No such file or directory [C:\Users\Matte
    o\Documents\paho.mqtt.cpp\build\src\paho-cpp-objs.vcxproj]
      token.cpp
    C:\Users\Matteo\Documents\paho.mqtt.cpp\src\mqtt/token.h(28,10): fatal  error C1083: Cannot open include file: 'MQTTAsync.h': No such file or directory [C:\Users\Matteo\Documents\
    paho.mqtt.cpp\build\src\paho-cpp-objs.vcxproj]
      topic.cpp
    C:\Users\Matteo\Documents\paho.mqtt.cpp\src\mqtt/topic.h(27,10): fatal  error C1083: Cannot open include file: 'MQTTAsync.h': No such file or directory [C:\Users\Matteo\Documents\
    paho.mqtt.cpp\build\src\paho-cpp-objs.vcxproj]
      will_options.cpp
    C:\Users\Matteo\Documents\paho.mqtt.cpp\src\mqtt/will_options.h(29,10): fatal  error C1083: Cannot open include file: 'MQTTAsync.h': No such file or directory [C:\Users\Matteo\Doc
    uments\paho.mqtt.cpp\build\src\paho-cpp-objs.vcxproj]
      Generating Code...
    

    What should I do?

    opened by Soraph 9
Releases(v1.2.0)
  • v1.2.0(Dec 27, 2020)

    This release brings in some missing MQTT v5 features, support for websocket headers and proxies, ALPN protocol lists, adds the builder pattern for options, and fixes a number of bugs in both the C++ library and the underlying C lib.

    Requires Paho C v1.3.8

    • Missing MQTT v5 features:
      • Ability to add properties to Subscribe and Unsubscribe packets (i.e. subscription identifiers)
      • "Disconnected" callback gives reason code and properties for server disconnect
    • New create_options that can be used to construct a client with new features:
      • Send while disconnected before the 1st successful connection
      • Output buffer can delete oldest messages when full
      • Can choose to clear the persistence store on startup
      • Select whether to persist QoS 0 messages
    • Started classes to create options using the Builder Pattern, with the create_options_builder, connect_options_builder, message_ptr_builder, etc.
    • User-defined websocket HTTP headers.
    • HTTP/S proxy support
    • Added ALPN protocol support to SSL/TLS options
    • SSL/TLS error and PSK callback support
    • Update connection callback support (change credentials when using auto-reconnect)
    • Updates to the sample apps:
      • Overall cleanup with better consistency
      • Example of using websockets and a proxy
      • User-based file persistence with simple encoding/encryption
      • Sharing a client between multiple threads
    • Converted the unit tests to use Catch2
    • All library exceptions are now properly derived from the mqtt::exception base class.
    • [#231] Added on_disconnected callback to handle receipt of disconnect packet from server.
    • [#211, #223, #235] Removed use of Log() function from the Paho C library.
    • [#227] Fixed race condition in thread-safe queue
    • [#224] & [#255] Subscribing to MQTT v3 broker with array of one topic causes segfault.
    • [#282] Ability to build Debian/Ubuntu package
    • [#300] Calling reconnect() was hanging forever, even when successful. In addition several of the synchronous client calls were hanging forever on failure. They now properly throw a timeout_error exception.
    • Several memory issues and bug fixes from updated Paho C library support.
    Source code(tar.gz)
    Source code(zip)
  • v1.1(Oct 12, 2019)

    This release was primarily to add MQTT v5 support and server responses.

    • MQTT v5 support:
      • Properties
        • New property class acts something like a std::variant to hold a property of any supported type.
        • New properties class is a collection type to hold all the properties for a single transmitted packet.
        • Properties can be added to outbound messages and obtained from received messages.
        • Properties can also be obtained from server responses to requests such as from a connect call. These are available in the token objects when they complete.
      • The client object tracks the desired MQTT version that the app requested and/or is currently connected at. Internally this is now required by the response_options the need to distinguish between pre-v5 and post-v5 callback functions.
      • MQTT v5 reason codes for requests are available via token objects when they complete. They are also available in exception objects that are thrown by tokens.
      • Support for subscibe options, like no local subscriptions, etc.
      • Sample applications were added showing how to do basic Remote Procedure Calls (RPC's) with MQTT v5 using the RESPONSE_TOPIC and CORRELATION_DATA properties. These are rpc_math_cli and rpc_math_srvr in the src/samples directory.
      • A sample "chat" application was added, showing how to use subscribe options, such as "no local".
    • More descriptive error messages (PR #154), integrated into the mqtt::exception class. MQTT v5 reason codes are also included in the exceptions when an error occurs.
    • Applications can (finally) get server responses from the various ACK packets. These are available through the tokens after they complete, as connect_response, subscribe_response, and unsubscribe_response.
    • The topic objects can be used to subscribe.
    • Applications can register individual callback functions instead of using a callback interface object. This allows easy use of lambda functions for callbacks.
    • The connect options can take a LWT as a plain message, via connect_options::set_will_message()
    • New unit tests have started using Catch2.
    • Tested with Paho C v1.3.1
    Source code(tar.gz)
    Source code(zip)
  • v1.0.1(Dec 12, 2018)

    This is a bug-fix released aimed mainly at issues with the build system and working towards more "modern" usage of CMake. In addition:

    • Support for Paho C v1.2.1
    • Fixed a number of build issues, particularly on Windows
    • Windows shared libraries (DLL's) now supported
    • Several minor bug fixes
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0(Jul 23, 2017)

    The initial Paho C++ Client library for memory-managed platforms (Linux, Windows, etc). Requires Paho C Client Library v1.2.

    Supports MQTT 3.1 & 3.1.1, SSL/TLS, Asynchronous & Synchronous interfaces, persistence and off-line buffering, automatic reconnect, and high availability.

    Source code(tar.gz)
    Source code(zip)
  • v0.5-prerelease(May 15, 2017)

    This was the initial, unsupported, version of the library that was publicly available for several years before the official v1.0 release (which introduced a number of breaking changes).

    Source code(tar.gz)
    Source code(zip)
Owner
Eclipse Foundation
Eclipse Foundation
Eclipse Mosquitto - An open source MQTT broker

Mosquitto is an open source implementation of a server for version 5.0, 3.1.1, and 3.1 of the MQTT protocol. It also includes a C and C++ client library, and the mosquitto_pub and mosquitto_sub utilities for publishing and subscribing.

Eclipse Foundation 6.9k Jan 9, 2023
A portable MQTT C client for embedded systems and PCs alike.

MQTT-C is an MQTT v3.1.1 client written in C. MQTT is a lightweight publisher-subscriber-based messaging protocol that is commonly used in IoT and net

Liam Bindle 570 Dec 29, 2022
Mongoose Embedded Web Server Library - a multi-protocol embedded networking library with TCP/UDP, HTTP, WebSocket, MQTT built-in protocols, async DNS resolver, and non-blocking API.

Mongoose - Embedded Web Server / Embedded Networking Library Mongoose is a networking library for C/C++. It implements event-driven non-blocking APIs

Cesanta Software 9k Jan 1, 2023
Control Hörmann doors drives directly via MQTT from Home Assistant

hoermann_door Control Hörmann doors drives directly via MQTT from Home Assistant

null 66 Nov 23, 2022
An MQTT-based Virtual Wall for ESP8266 Devices and Gerber files to make the IR hat; this code and board can easily be adapted to be ANY infrared controller/remote!

Roomba-Virtual-Wall-ESP8266-MQTT An MQTT-based Virtual Wall for ESP8266 Devices I made this based off of the IRSend, IRremoteESP8266, and EspMQTTClien

null 8 Sep 20, 2021
WiFi/MQTT Code For the ThingPulse ESPGateway

ESP32-Paxcounter with ThingPulse ESPGateway This project lets you run the ESP32-Paxcounter project on the ThingPulse ESPGateway. The ESPGateway has tw

Daniel Eichhorn 6 Aug 13, 2022
Wifi MQTT Data Logging via an esp8266 for the Ikea VINDRIKTNING PM2.5 air quality sensor

MQTT connectivity for the Ikea VINDRIKTNING This repository contains an ESP8266 firmware, which adds MQTT to the Ikea VINDRIKTNING PM2.5 air quality s

Sören Beye 943 Dec 31, 2022
This is a MQTT-enabled, compact weather station powered by a Wemos D1 minicontroller and built with 3D-printed parts

This is a MQTT-enabled, compact weather station powered by a Wemos D1 minicontroller and built with 3D-printed parts. It supports OTA updates.

65397 1 Feb 10, 2022
Show pressure & temperature readings from Home Assistant/MQTT on a mini display

home-assistant-barometer-display A mini Home Assistant display to show pressure & temperature readings (and made to look pretty with 'freeform pcb' br

David Barton 4 Jan 4, 2022
AWS FreeRTOS MQTT demo project running on the NXP i.MXRT1050-EVKB.

AWS MQTT demo example project Click to import in Keil Studio Cloud: Board: NXP IMXRT1050-EVKB The tables below list the device configuration for this

Arm - Keil tools 1 Oct 18, 2021
Use an esp32 as gateway for the Eqiva Bluetooth smart lock to integrate it in Home Assistant as MQTT lock

esp32-keyble-homeassistant Use an esp32 as gateway for the Eqiva Bluetooth smart lock to integrate it in Home Assistant as MQTT lock Based on the grea

null 8 Nov 22, 2022
RPI Pico WIFI via ESP-01S, LWESP, FreeRTOS, and MQTT example

RPIPicoRTOSMQTT RPI Pico WIFI via ESP-01S, LWESP, FreeRTOS, and MQTT example Demo code for RPI Pico using ESP-01S for wifi connection over uart. With

Dr Jon Durrant 2 Dec 2, 2021
Google IOT MQTT Sample

This is an adaptation of Zephyr's Google Cloud IoT Core MQTT sample samples/net/cloud/google_iot_mqtt for the nRF9160-DK, using modem features to offload certificate storage, TLS and JWT calculation.

Jeffrey Urban 5 Jan 27, 2022
AirGradient Pushing to InfluxDB or MQTT

Custom AirGradient Sketch AirGradient’s sensor set up is a good base and reasonably affordable. This Arduino sketch allows you to integrate with a loc

null 8 Apr 6, 2022
16 Channel Current Meter to MQTT Gateway

16 Channel Current Meter to MQTT Gateway This sketch runs on an ESP8266 and reads data from 16 Channel Current Measurement Module over RS485 Modbus an

null 5 Nov 11, 2022
Triton Python and C++ client libraries and example, and client examples for go, java and scala.

Triton Client Libraries and Examples To simplify communication with Triton, the Triton project provides several client libraries and examples of how t

Triton Inference Server 228 Jan 5, 2023
VEngine-Client - vEngine: Official Client Module

━ S Y N O P S I S ━ Maintainer(s): Aviril, Tron vEngine is Next-Gen Sandbox-Engine being crafted in C++. In contrast to UE/Unity/ReverseEngineered-Mod

ᴠ : ꜱᴛᴜᴅɪᴏ 15 Sep 7, 2022
Pyth-client - client API for on-chain pyth programs

pyth-client client API for on-chain pyth programs Build Instructions # depends on openssl apt install libssl-dev # depends on libz apt install zlib1g

Pyth Network 115 Dec 16, 2022
Webdav-client-cpp - C++ WebDAV Client provides easy and convenient to work with WebDAV-servers.

WebDAV Client Package WebDAV Client provides easy and convenient to work with WebDAV-servers: Yandex.Disk Dropbox Google Drive Box 4shared ownCloud ..

Cloud Polis 103 Jan 1, 2023