{"id":13546547,"url":"https://github.com/256dpi/arduino-mqtt","last_synced_at":"2025-04-08T04:15:40.105Z","repository":{"id":23967485,"uuid":"27349944","full_name":"256dpi/arduino-mqtt","owner":"256dpi","description":"MQTT library for Arduino","archived":false,"fork":false,"pushed_at":"2024-08-30T16:31:38.000Z","size":468,"stargazers_count":1051,"open_issues_count":27,"forks_count":238,"subscribers_count":60,"default_branch":"master","last_synced_at":"2025-04-01T03:35:43.309Z","etag":null,"topics":["arduino","iot","mqtt"],"latest_commit_sha":null,"homepage":"","language":"C","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/256dpi.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2014-11-30T21:02:07.000Z","updated_at":"2025-03-21T16:44:01.000Z","dependencies_parsed_at":"2024-01-15T20:55:34.022Z","dependency_job_id":"b3d5253f-3dec-45ca-b2b4-0bf40111aba2","html_url":"https://github.com/256dpi/arduino-mqtt","commit_stats":{"total_commits":537,"total_committers":18,"mean_commits":"29.833333333333332","dds":0.07076350093109873,"last_synced_commit":"849b7a5b3dc6cfca189a03990160f1c1d4bdae0b"},"previous_names":[],"tags_count":50,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/256dpi%2Farduino-mqtt","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/256dpi%2Farduino-mqtt/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/256dpi%2Farduino-mqtt/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/256dpi%2Farduino-mqtt/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/256dpi","download_url":"https://codeload.github.com/256dpi/arduino-mqtt/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247773719,"owners_count":20993639,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["arduino","iot","mqtt"],"created_at":"2024-08-01T12:00:39.959Z","updated_at":"2025-04-08T04:15:40.077Z","avatar_url":"https://github.com/256dpi.png","language":"C","funding_links":[],"categories":["C","Libraries","Protocol Library"],"sub_categories":["MQTT"],"readme":"# arduino-mqtt\n\n[![Test](https://github.com/256dpi/arduino-mqtt/actions/workflows/test.yml/badge.svg)](https://github.com/256dpi/arduino-mqtt/actions/workflows/test.yml)\n[![GitHub release](https://img.shields.io/github/release/256dpi/arduino-mqtt.svg)](https://github.com/256dpi/arduino-mqtt/releases)\n\nThis library bundles the [lwmqtt](https://github.com/256dpi/lwmqtt) MQTT 3.1.1 client and adds a thin wrapper to get an Arduino like API.\n\nDownload the latest version from the [release](https://github.com/256dpi/arduino-mqtt/releases) section. Or even better use the built-in Library Manager in the Arduino IDE and search for \"lwmqtt\".\n\nThe library is also available on [PlatformIO](https://platformio.org/lib/show/617/MQTT). You can install it by running: `pio lib install \"256dpi/MQTT\"`. \n\n## Compatibility\n\nThe following examples show how you can use the library with various Arduino compatible hardware:\n\n- [Arduino Yun \u0026 Yun-Shield](https://github.com/256dpi/arduino-mqtt/blob/master/examples/ArduinoYun/ArduinoYun.ino) ([Secure](https://github.com/256dpi/arduino-mqtt/blob/master/examples/ArduinoYunSecure/ArduinoYunSecure.ino))\n- [Arduino Ethernet Shield](https://github.com/256dpi/arduino-mqtt/blob/master/examples/ArduinoEthernetShield/ArduinoEthernetShield.ino)    \n- [Arduino WiFi Shield](https://github.com/256dpi/arduino-mqtt/blob/master/examples/ArduinoWiFiShield/ArduinoWiFiShield.ino)\n- [Adafruit HUZZAH ESP8266](https://github.com/256dpi/arduino-mqtt/blob/master/examples/AdafruitHuzzahESP8266/AdafruitHuzzahESP8266.ino) ([Secure](https://github.com/256dpi/arduino-mqtt/blob/master/examples/AdafruitHuzzahESP8266Secure/AdafruitHuzzahESP8266Secure.ino))\n- [Arduino WiFi101 Shield](https://github.com/256dpi/arduino-mqtt/blob/master/examples/ArduinoWiFi101/ArduinoWiFi101.ino) ([Secure](https://github.com/256dpi/arduino-mqtt/blob/master/examples/ArduinoWiFi101Secure/ArduinoWiFi101Secure.ino))\n- [Arduino MKR GSM 1400](https://github.com/256dpi/arduino-mqtt/blob/master/examples/ArduinoMKRGSM1400/ArduinoMKRGSM1400.ino) ([Secure](https://github.com/256dpi/arduino-mqtt/blob/master/examples/ArduinoMKRGSM1400Secure/ArduinoMKRGSM1400Secure.ino))\n- [Arduino MKR NB 1500](https://github.com/256dpi/arduino-mqtt/blob/master/examples/ArduinoMKRNB1500/ArduinoMKRNB1500.ino)\n- [ESP32 Development Board](https://github.com/256dpi/arduino-mqtt/blob/master/examples/ESP32DevelopmentBoard/ESP32DevelopmentBoard.ino) ([Secure](https://github.com/256dpi/arduino-mqtt/blob/master/examples/ESP32DevelopmentBoardSecure/ESP32DevelopmentBoardSecure.ino))\n\nOther shields and boards should also work if they provide a [Client](https://www.arduino.cc/en/Reference/ClientConstructor) based network implementation.\n\n**Check out the [Wiki](https://github.com/256dpi/arduino-mqtt/wiki) to find more examples.**\n\n## Notes\n\n- The maximum size for packets being published and received is set by default to 128 bytes. To change the buffer sizes, you need to use `MQTTClient client(256)` or `MQTTClient client(256, 512)` instead of just `MQTTClient client` at the top of your sketch. A single value denotes both the read and write buffer size, two values specify them separately. **Beginning with version 2.5.2, the message payload is sent directly during publishing. Therefore, the write buffer is only needed to encode the packet header and topic, for which the default 128 bytes should be enough. However, the receiving of messages is still fully constrained by the read buffer, which may be increased if necessary.**\n\n- On the ESP8266 it has been reported that an additional `delay(10);` after `client.loop();` fixes many stability issues with WiFi connections.\n\n- To use the library with shiftr.io, you need to provide the instance name (username) and token secret (password) as the second and third argument to `client.connect(client_id, username, password)`. \n\n## Example\n\nThe following example uses an Arduino MKR1000 to connect to the public shiftr.io instance. You can check on your device after a successful connection here: https://www.shiftr.io/try.\n\n```c++\n#include \u003cSPI.h\u003e\n#include \u003cWiFi101.h\u003e\n#include \u003cMQTT.h\u003e\n\nconst char ssid[] = \"ssid\";\nconst char pass[] = \"pass\";\n\nWiFiClient net;\nMQTTClient client;\n\nunsigned long lastMillis = 0;\n\nvoid connect() {\n  Serial.print(\"checking wifi...\");\n  while (WiFi.status() != WL_CONNECTED) {\n    Serial.print(\".\");\n    delay(1000);\n  }\n\n  Serial.print(\"\\nconnecting...\");\n  while (!client.connect(\"arduino\", \"public\", \"public\")) {\n    Serial.print(\".\");\n    delay(1000);\n  }\n\n  Serial.println(\"\\nconnected!\");\n\n  client.subscribe(\"/hello\");\n  // client.unsubscribe(\"/hello\");\n}\n\nvoid messageReceived(String \u0026topic, String \u0026payload) {\n  Serial.println(\"incoming: \" + topic + \" - \" + payload);\n\n  // Note: Do not use the client in the callback to publish, subscribe or\n  // unsubscribe as it may cause deadlocks when other things arrive while\n  // sending and receiving acknowledgments. Instead, change a global variable,\n  // or push to a queue and handle it in the loop after calling `client.loop()`.\n}\n\nvoid setup() {\n  Serial.begin(115200);\n  WiFi.begin(ssid, pass);\n\n  // Note: Local domain names (e.g. \"Computer.local\" on OSX) are not supported\n  // by Arduino. You need to set the IP address directly.\n  client.begin(\"public.cloud.shiftr.io\", net);\n  client.onMessage(messageReceived);\n\n  connect();\n}\n\nvoid loop() {\n  client.loop();\n\n  if (!client.connected()) {\n    connect();\n  }\n\n  // publish a message roughly every second.\n  if (millis() - lastMillis \u003e 1000) {\n    lastMillis = millis();\n    client.publish(\"/hello\", \"world\");\n  }\n}\n```\n\n## API\n\nCreate the object with:\n\n```c++\nMQTTClient()\nMQTTClient(int bufSize)\nMQTTClient(int readBufSize, int writeBufSize)\n```\n\n- `MQTTClient` has two buffers. One for read and one for write. Default buffer size is 128 bytes. In summary are 256 bytes are used for buffers.\n- The `bufSize` option sets `readBufSize` and `writeBufSize` to the same value.\n\nInitialize the object using the hostname of the broker, the brokers port (default: `1883`) and the underlying Client class for network transport:\n\n```c++\nvoid begin(Client \u0026client);\nvoid begin(const char hostname[], Client \u0026client);\nvoid begin(const char hostname[], int port, Client \u0026client);\nvoid begin(IPAddress address, Client \u0026client);\nvoid begin(IPAddress address, int port, Client \u0026client);\n```\n\n- Specify port `8883` when using secure clients for encrypted connections.\n- Local domain names (e.g. `Computer.local` on OSX) are not supported by Arduino. You need to set the IP address directly.\n\nThe hostname and port can also be changed after calling `begin()`:\n\n```c++\nvoid setHost(const char hostname[]);\nvoid setHost(const char hostname[], int port);\nvoid setHost(IPAddress address);\nvoid setHost(IPAddress address, int port);\n```\n\nSet a will message (last testament) that gets registered on the broker after connecting. `setWill()` has to be called before calling `connect()`:\n\n```c++\nvoid setWill(const char topic[]);\nvoid setWill(const char topic[], const char payload[]);\nvoid setWill(const char topic[], const char payload[], bool retained, int qos);\nvoid clearWill();\n```\n\nRegister a callback to receive messages:\n\n```c++\nvoid onMessage(MQTTClientCallbackSimple);\n// Callback signature: void messageReceived(String \u0026topic, String \u0026payload) {}\n\nvoid onMessage(MQTTClientCallbackSimpleFunction cb);\n// Callback signature: std::function\u003cvoid(String \u0026topic, String \u0026payload)\u003e\n\nvoid onMessageAdvanced(MQTTClientCallbackAdvanced);\n// Callback signature: void messageReceived(MQTTClient *client, char topic[], char bytes[], int length) {}\n\nvoid onMessageAdvanced(MQTTClientCallbackAdvancedFunction cb);\n// Callback signature: std::function\u003cvoid(MQTTClient *client, char topic[], char bytes[], int length)\u003e\n```\n\n- The set callback is mostly called during a call to `loop()` but may also be called during a call to `subscribe()`, `unsubscribe()` or `publish() // QoS \u003e 0` if messages have been received before receiving the required acknowledgement. Therefore, it is strongly recommended to not call `subscribe()`, `unsubscribe()` or `publish() // QoS \u003e 0` directly in the callback.\n- In case you need a reference to an object that manages the client, use the `void * ref` property on the client to store a pointer, and access it directly from the advanced callback.\n- If the platform supports `\u003cfunctional\u003e` you can directly register a function wrapper.\n\nSet more advanced options:\n\n```c++\nvoid setKeepAlive(int keepAlive);\nvoid setCleanSession(bool cleanSession);\nvoid setTimeout(int timeout);\nvoid setOptions(int keepAlive, bool cleanSession, int timeout);\n```\n\n- The `keepAlive` option controls the keep alive interval in seconds (default: 10).\n- The `cleanSession` option controls the session retention on the broker side (default: true).\n- The `timeout` option controls the default timeout for all commands in milliseconds (default: 1000).\n\nSet a custom clock source \"custom millis\" callback to enable deep sleep applications:\n\n```c++\nvoid setClockSource(MQTTClientClockSource);\n// Callback signature: uint32_t clockSource() {}\n```\n\n- The specified callback is used by the internal timers to get a monotonic time in milliseconds. Since the clock source for the built-in `millis` is stopped when the Arduino goes into deep sleep, you need to provide a custom callback that first syncs with a built-in or external Real Time Clock (RTC). You can pass `NULL` to reset to the default implementation.\n\nConnect to broker using the supplied client ID and an optional username and password:\n\n```c++\nbool connect(const char clientID[], bool skip = false);\nbool connect(const char clientID[], const char username[], bool skip = false);\nbool connect(const char clientID[], const char username[], const char password[], bool skip = false);\n```\n\n- If `password` is present but `username` is absent, the client will fall back to an empty username.\n- If the `skip` option is set to true, the client will skip the network level connection and jump to the MQTT level connection. This option can be used in order to establish and verify TLS connections manually before giving control to the MQTT client. \n- The functions return a boolean that indicates if the connection has been established successfully (true).\n\nPublish a message to the broker with an optional payload, which can be a string or binary:\n\n```c++\nbool publish(const String \u0026topic);\nbool publish(const char topic[]);\nbool publish(const String \u0026topic, const String \u0026payload);\nbool publish(const String \u0026topic, const String \u0026payload, bool retained, int qos);\nbool publish(const char topic[], const String \u0026payload);\nbool publish(const char topic[], const String \u0026payload, bool retained, int qos);\nbool publish(const char topic[], const char payload[]);\nbool publish(const char topic[], const char payload[], bool retained, int qos);\nbool publish(const char topic[], const char payload[], int length);\nbool publish(const char topic[], const char payload[], int length, bool retained, int qos);\n```\n\n- Beginning with version 2.5.2, payloads of arbitrary length may be published, see [Notes](#notes).\n- The functions return a boolean that indicates if the publishing has been successful (true).\n\nObtain the last used packet ID and prepare the publication of a duplicate message using the specified packet ID:\n\n```c++\nuint16_t lastPacketID();\nvoid prepareDuplicate(uint16_t packetID);\n```\n\n- These functions may be used to implement a retry logic for failed publications of QoS1 and QoS2 messages.\n- The `lastPacketID()` function can be used after calling `publish()` to obtain the used packet ID.\n- The `prepareDuplicate()` function may be called before `publish()` to temporarily change the next used packet ID and flag the message as a duplicate.\n\nSubscribe to a topic:\n\n```c++\nbool subscribe(const String \u0026topic);\nbool subscribe(const String \u0026topic, int qos); \nbool subscribe(const char topic[]);\nbool subscribe(const char topic[], int qos);\n```\n\n- The functions return a boolean that indicates if the subscription has been successful (true).\n\nUnsubscribe from a topic:\n\n```c++\nbool unsubscribe(const String \u0026topic);\nbool unsubscribe(const char topic[]);\n```\n\n- The functions return a boolean that indicates if the unsubscription has been successful (true).\n\nSends and receives packets:\n\n```c++\nbool loop();\n```\n\n- This function should be called in every `loop`.\n- The function returns a boolean that indicates if the loop has been successful (true).\n\nCheck if the client is currently connected:\n\n```c++\nbool connected();\n```\n\nCheck whether a session was present at the time of the last connect:\n\n```c++\nbool sessionPresent();\n```\n\nConfigure dropping of overflowing messages (exceeding read buffer) and checking the count of dropped messages:\n\n```c++\nvoid dropOverflow(bool enabled);\nuint32_t droppedMessages();\n```\n\nAccess low-level information for debugging:\n\n```c++\nlwmqtt_err_t lastError();\nlwmqtt_return_code_t returnCode();\n```\n\n- The error codes can be found [here](https://github.com/256dpi/lwmqtt/blob/master/include/lwmqtt.h#L15).\n- The return codes can be found [here](https://github.com/256dpi/lwmqtt/blob/master/include/lwmqtt.h#L260).\n\nDisconnect from the broker:\n\n```c++\nbool disconnect();\n```\n\n- The function returns a boolean that indicates if the disconnect has been successful (true).\n\n## Release Management\n\n- Update version in `library.properties`.\n- Create release on GitHub.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F256dpi%2Farduino-mqtt","html_url":"https://awesome.ecosyste.ms/projects/github.com%2F256dpi%2Farduino-mqtt","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F256dpi%2Farduino-mqtt/lists"}