Skip to content
Go to file

Latest commit


Git stats


Failed to load latest commit information.
Latest commit message
Commit time

Losant Arduino MQTT Client

The Losant Arduino MQTT client provides a simple way for your Arduino-based things to connect and communicate with the Losant Enterprise IoT Platform.

Installation for PlatformIO

The latest stable version is available in PlatformIO and can be installed adding dependency (lib_deps) to your project configuration file platformio.ini

platform = ...
board = ...
framework = arduino
lib_deps = losant-mqtt-arduino

Using PlatformIO IDE requires a single include directive:

#include <Losant.h>

Installation for the Arduino IDE

The Losant Arduino MQTT client is distributed as an Arduino library. It can be installed in two ways:

  1. Download a zip of this repository and include it into your Arduino Sketch. Select Sketch -> Include Library -> Add .ZIP library from the Arduino menu.
  2. Clone the contents of the repository into Arduino's library folder on your system. This location changes based on OS, but on Mac and Windows it's typically at Documents / Arduino / libraries.

Once installed, using the library requires a single include directive.

#include <Losant.h>


The Losant Arduino MQTT client depends on ArduinoJson and MQTT Client. These libraries must be installed before using the Losant MQTT client. When using, these dependencies are installed automatically, but when using the Arduino IDE they must be installed manually. Please refer to their documentation for specific installation instructions.

Important Considerations

You’ll possibly hit the default MQTT packet size limit defined in the Losant Arduino MQTT Client library. Unfortunately the packet is blocked before reaching any of your code, so it’s hard to debug. It simply looks like the command was never received. For example:

{ "foo" : "bar" } works, whereas { "somethingLarger" : "with a longer value" } doesn’t work. This is because the default packet size is 256, which provides enough room for the command meta info and a small payload. Fortunately, this is easily fixed by defining a larger value for MQTT_MAX_PACKET_SIZE in your Arduino code.


Below is a basic example of using the Losant Arduino MQTT client. For specific examples for various boards, please refer to the examples folder.

#include <WiFi101.h>
#include <Losant.h>

// WiFi credentials.
const char* WIFI_SSID = "WIFI_SSID";
const char* WIFI_PASS = "WIFI_PASS";

// Losant credentials.
const char* LOSANT_DEVICE_ID = "my-device-id";
const char* LOSANT_ACCESS_KEY = "my-app-key";
const char* LOSANT_ACCESS_SECRET = "my-app-secret";

const int BUTTON_PIN = 14;
const int LED_PIN = 12;

bool ledState = false;

WiFiSSLClient wifiClient;

LosantDevice device(LOSANT_DEVICE_ID);

// Toggles and LED on or off.
void toggle() {
  Serial.println("Toggling LED.");
  ledState = !ledState;
  digitalWrite(LED_PIN, ledState ? HIGH : LOW);

// Called whenever the device receives a command from the Losant platform.
void handleCommand(LosantCommand *command) {
  Serial.print("Command received: ");

  if(strcmp(command->name, "toggle") == 0) {

void connect() {


  while (WiFi.status() != WL_CONNECTED) {

  // Connect to Losant.
  device.connectSecure(wifiClient, LOSANT_ACCESS_KEY, LOSANT_ACCESS_SECRET);

  while(!device.connected()) {

void setup() {
  pinMode(LED_PIN, OUTPUT);

  // Register the command handler to be called when a command is received
  // from the Losant platform.


void buttonPressed() {
  Serial.println("Button Pressed!");

  // Losant uses a JSON protocol. Construct the simple state object.
  // { "button" : true }
  StaticJsonDocument<200> jsonBuffer;
  JsonObject root =<JsonObject>();
  root["button"] = true;

  // Send the state to Losant.

int buttonState = 0;

void loop() {

  bool toReconnect = false;

  if(WiFi.status() != WL_CONNECTED) {
    Serial.println("Disconnected from WiFi");
    toReconnect = true;

  if(!device.connected()) {
    Serial.println("Disconnected from Losant");
    toReconnect = true;

  if(toReconnect) {


  int currentRead = digitalRead(BUTTON_PIN);

  if(currentRead != buttonState) {
    buttonState = currentRead;
    if(buttonState) {


Losant State and Commands

State and commands are the main two communication constructs of the Losant platform. A state represents a current snapshot of the device at a moment in time. On typical IoT devices, attributes of a device's state typically correspond to individual sensors (e.g. "temperature", "light level", or "sound level"). States can be reported to Losant as often as needed.

Commands allow you to control your device remotely. What commands a device supports is entirely up to the device's firmware. A command is comprised of a name and an optional payload. The name indicates what command the device should invoke (e.g. "start recording") and the payload provide parameters to the command (e.g. { "resolution": 1080 }).

API Documentation


The LosantDevice class represents a single connection to the Losant platform. Use this class to report state information and subscribe to commands.

LosantDevice::LosantDevice(const char* id)

Losant device constructor. The only parameter is the device ID. A Losant device ID can be obtained by registering your device using the Losant dashboard.

LosantDevice device('my-device-id');


Losant device constructor that does not require a device ID. The ID can be set at a later time using setId() The ID must be set before connect() can be called.

LosantDevice device;


Gets the device ID that was set through the constructor or setId() call.

LosantDevice device('my-device-id');
const *char deviceId = device.getId();


Sets the device ID. Typically called if the ID was not passed through the constructor.

LosantDevice device;
LosantDevice device('my-device-id');
const *char deviceId = device.getId();

LosantDevice::connect(Client& client, const char* key, const char* secret)

Creates an unsecured connection to the Losant platform.

WiFiClient client;


LosantDevice device('my-device-id');
device.connect(client, 'my-access-key', 'my-access-secret');

LosantDevice::connectSecure(Client& client, const char* key, const char* secret)

Creates a TLS encrypted connection to the Losant platform.

WiFiSSLClient client;


LosantDevice device('my-device-id');
device.connectSecure(client, 'my-access-key', 'my-access-secret');

LosantDevice::onCommand(CommandCallback callback)

Registers a function that will be called whenever a command is received from the Losant platform.

void handleCommand(LosantCommand *command) {
  Serial.print("Command received: ");

  // { "foo" : 10 }
  JsonObject payload = *command->payload;
  long bar = payload["foo"];

LosantDevice device('my-device-id');
device.connectSecure(client, 'my-access-key', 'my-access-secret');

The command callback function is passed a LosantCommand object with details about the command. These include name, time, and payload. name is a string containing the command's name. time is the UTC ISO string of the date and time when the command was received by the Losant platform. payload is a JsonObject with whatever arguments was passed to the command when it was sent.

LosantDevice::sendState(JsonObject& state)

Sends a state update to Losant. The state of an object is defined as a simple Json object with keys and values. Refer to the ArduinoJson library for detailed documentation.

StaticJsonDocument<200> jsonBuffer;
JsonObject state =<JsonObject>();
state["temperature"] = 72;

// Send the state to Losant.


Loops the underlying Client to perform any required MQTT communication. Must be called periodically, no less than once every few seconds.


Copyright (c) 2020 Losant IoT, Inc


Arduino MQTT Client for connecting devices to the Losant IoT Platform



You can’t perform that action at this time.