mqtt-c Documentation

repository·master·Indexed 21 days ago

https://github.com/liambindle/mqtt-c

A lightweight, portable MQTT v3.1.1 client written in ANSI C (C89). Designed for embedded systems and PCs, it features a Platform Abstraction Layer (PAL) for easy porting and full thread safety. The library consists of mqtt.c and mqtt_pal.c, providing core functions such as mqtt_init(), mqtt_connect(), mqtt_subscribe(), and mqtt_publish().

Tokens
680
Snippets
2
Records
4
Agent score
25%

What's inside mqtt-c

  1. Port MQTT-C to a new platform using the PAL

    master
    MQTT-C achieves portability through a Platform Abstraction Layer (PAL) implemented in mqtt_pal.h and mqtt_pal.c. These files define the types and function calls required by the core MQTT logic. To port MQTT-C to a new hardware platform or operating system, you must implement the interfaces defined in the PAL.
  2. Quickstart: Basic MQTT-C usage

    master

    To use MQTT-C, follow these core steps:

    1. Instantiate a struct mqtt_client.
    2. Initialize the client using mqtt_init().
    3. Connect to a broker using mqtt_connect().
    4. Use mqtt_subscribe() to listen to topics or mqtt_publish() to send messages.

    MQTT-C is designed to be portable, thread-safe, and lightweight, making it suitable for both embedded systems and PCs.

        struct mqtt_client client; /* instantiate the client */
        mqtt_init(&client, ...);   /* initialize the client */
    
        mqtt_connect(&client, ...); /* send a connection request to the broker. */
    
        /* subscribe to "toaster/temperature" with a max QoS level of 0 */
        mqtt_subscribe(&client, "toaster/temperature", 0);
    
        /* publish coffee temperature with a QoS level of 1 */
        int temperature = 67;
        mqtt_publish(&client, "coffee/temperature", &temperature, sizeof(int), MQTT_PUBLISH_QOS_1);
  3. Run MQTT-C unit tests

    master

    MQTT-C uses the cmocka unit testing framework. You must have cmocka installed to build and run tests.

    On UNIX-like machines, use the provided Makefile to build the tests and examples into the bin/ directory:

    $ make all

    To run the tests, execute the binary in the bin/ directory. You can optionally provide an address and port for an MQTT broker. If no address is provided, it defaults to the Mosquitto MQTT Test Server (test.mosquitto.org) on port 1883.

    $ make all
    $ ./bin/tests [address [port]]
  4. Build and integrate MQTT-C

    master

    MQTT-C consists of only two source files: mqtt.c and mqtt_pal.c. These are ANSI C (C89) compatible and can be compiled with any C compiler.

    To integrate into your project:

    1. Include the header: #include <mqtt.h>.
    2. Compile mqtt.c and mqtt_pal.c along with your application code.

    Alternatively, you can use the provided CMake configuration or the included Makefile for convenience.