Skip to content

Latest commit

 

History

History
2954 lines (2396 loc) · 167 KB

MQTTAPIS.md

File metadata and controls

2954 lines (2396 loc) · 167 KB

Cayenne MQTT API

Overview

The Cayenne MQTT API is used to connect any device that you have with the Cayenne Cloud. After connecting your device you can send data from your device to the Cayenne dashboard and display it using widgets. You may also receive commands from Cayenne, allowing remote control and automation of your devices.

About MQTT

MQTT is a lightweight messaging protocol designed to be used on top of TCP/IP. It uses an event and message (publish-subscribe) methodology that was designed especially for connections where small footprints, unreliable and/or limited bandwidth connections are found. This type of pattern is especially suited for IoT devices that get deployed in the field and often run on battery power and on constrained networks. With MQTT, the publish-subscribe pattern makes use of a broker that is responsible for distributing messages to clients.Clients can subscribe to varying levels of messages, depending upon how much or what kind of data they are interested.

Using MQTT with Cayenne

MQTT is the preferred transport and API for sending data to the Cayenne Cloud, or for devices that receive commands from Cayenne. The Cayenne Cloud acts as a broker, managing the various sensor and actuator client devices that wish to send and receive data using the Cayenne Cloud.

Cayenne MQTT is straightforward and easy to use, offering several different ways of connecting your data to Cayenne.

Option 1: Use the Cayenne MQTT Libraries

Using one of our libraries is the easiest way to get started using MQTT with Cayenne. The Cayenne libraries bundle an MQTT clientand all of the code examples you'll need to get your board connected and using MQTT with Cayenne.

We have prepared walkthroughs and libraries for some of the most common toolchain/IDE combinations to help get you up and running as quickly as possible. If you would like to use one of our libraries, the easiest way to get started is to jump to a section below and read through the information and guides provided there.

  • Arduino MQTT Library - For Beginner users. This is the easiest way to get started with using Arduino MQTT in your project. This section covers installing and configuring the popular Arduino IDE to use Cayenne's Arduino MQTT library. It also includes a walkthrough of setting up an Arduino board, sending sensor data to Cayenne and controlling an actuator from the Cayenne dashboard.

  • mbed MQTT Library - For Intermediate users. This section walks you through using the mbed C++ MQTT Library in your project that uses the mbed IDE. It includes an example of connecting a Nucleo board to Cayenne, writing code to send sensor data as well as control an onboard LED from the Cayenne dashboard.

  • C++ MQTT Library - For Advanced users. This section discusses the steps needed to make use of the Cayenne C++ MQTT library in your code. It also includes advice from the Cayenne team as to which areas of the code need to be updated/customized in order to implement support for new boards in a Cayenne library.

  • Embedded C MQTT Library - For Advanced users. This section discusses the steps needed to make use of the Embedded C MQTT library in your code. It also includes advice from the Cayenne team as to which areas of the code need to be updated/customized in order to implement support for new boards in a Cayenne library.

Option 2: Use raw MQTT API functions

If you are integrating Cayenne into your existing or custom program, you may wish to only use raw MQTT calls for interacting with Cayenne. Typically you will have already chosen your own MQTT client, will already have implemented your own networking code, and you just need the Publish-Subscribe details for Cayenne’s MQTT API.

If you fall into this camp, you can jump straight to the MQTT Messaging Topics section where you’ll find the details for Cayenne's MQTT calls. We have also prepared a tutorial for using an MQTT client to manually publish and subscribe data so that you can test out using MQTT with Cayenne.

  • Manually Publishing / Subscribing - This will walk you through using the MQTT.fx client to manually publish and subscribe to Cayenne. This can help you test out using MQTT with Cayenne without having to connect an actual board or sensors. This is a great way to become familiar with the fundamentals of using MQTT with Cayenne.

Option 3: use HTTP to push MQTT data

If you are interesting to push external data into a virtual device you can use Cayenne API HTTP endpoint to do so.

POST https://api.mydevices.com/things/MQTT_CLIENT_ID/data
Header Value
Authorization Basic MQTT_USERNAME:MQTT_PASSWORD
Content-Type application/json

Request Payload

[
  {
    "channel": 1,
    "value": 16.4,
    "type": "temp",
    "unit": "c"
 },
 {
    "channel": 2,
    "value": 75,
    "type": "rel_hum",
    "unit": "p"
 },
 {
    "channel": 5,
    "value": 75,
    "type": "batt",
    "unit": "v"
 },
 {
    "channel": 10,
    "value": 1,
    "type": "digital_sensor",
    "unit": "d"
 },
 {...}
]

The payload must be a JSON array of objects, each having channel, value, type and unit porperties. Refer to the list of our supported data types for the type and unit properties.

MQTT Clients

To interact with an MQTT broker you’ll need an MQTT client. Here’s a quick list of MQTT clients and resources:

Paho: The Eclipse Paho project provides open-source MQTT clients for C/C++, Python, Java, Javascript, Go and C#. If you are using one of Cayenne’s libraries, the Paho client is bundled in the library to make using MQTT with Cayenne easy.

MQTT.fx: A JavaFX based MQTT Client.

MQTT Lens: A Google Chrome extension that connects to an MQTT broker and is able to publish and subscribe to MQTT topics.

MQTT Inspector: A general MQTT testing app for iOS (iPhone and iPad).

Libraries

Using one of our libraries is the easiest way to get started using MQTT with Cayenne. The Cayenne libraries bundle an MQTT client and all of the code examples you'll need to get your board connected and using MQTT with Cayenne.

Cayenne Arduino MQTT

Includes everything you need for using Cayenne and MQTT in your Arduino IDE based project.

  • The Arduino MQTT Library is available directly through the Arduino IDE Library Manager. This is the recommended way of obtaining this library. See Add MQTT Library to Arduino IDE for a walkthrough of performing this.

  • Documentation - Covers installing and configuring the popular Arduino IDE to use Cayenne's Arduino MQTT library. It also includes a walkthrough of setting up an Arduino board and sending sensor data to Cayenne.

Cayenne mbed MQTT

Includes everything you need for using Cayenne and MQTT in your mbed IDE based project.

  • Refer to the README located in the mbed MQTT Github for information on using & obtaining mbed library versions.
  • Documentation - Walks you through using the mbed C++ MQTT Library in your project that uses the mbed IDE. It includes an example of connecting a Nucleo board to Cayenne, writing code to send sensor data as well as control an onboard LED from the Cayenne dashboard.

Cayenne C++ MQTT

Includes everything you need for using Cayenne and MQTT in your project that uses the C++ language.

  • Refer to the README located in the C++ Github for information on using & obtaining C++ library versions.
  • Documentation - Discusses the steps needed to make use of the Cayenne C++ MQTT library in your code. It also includes advice from the Cayenne team as to which areas of the code need to be updated/customized in order to implement support for new boards in a Cayenne library.

Cayenne Embedded C MQTT

Includes everything you need for using Cayenne and MQTT in your project that uses the C language.

  • Refer to the README located in the Embedded C Github for information on using & obtaining C++ library versions.
  • Documentation - Discusses the steps needed to make use of the Embedded C MQTT library in your code. It also includes advice from the Cayenne team as to which areas of the code need to be updated/customized in order to implement support for new boards in a Cayenne library.

Using the MQTT Libraries

Create a Cayenne account

In order to use the Cayenne MQTT API, you will need to first create a Cayenne account. Visit the Cayenne website and create an account.


get started for free


account sign up

After creating your account, Cayenne will ask you which type of device you wish to add to your project. To add a device using the API, select Bring Your Own Thing from the list of devices presented. You will then be taken to a screen with details needed to help you connect your board to Cayenne.


Step 1 - Select device category

Using Arduino MQTT

The Cayenne Arduino MQTT library gives you everything you need to quickly get your board connected with Cayenne using MQTT and the Arduino IDE. Using the Arduino IDE is a fast and easy way to program your Arduino board. In this section we will walk you through setting up the Arduino IDE software so that you can write code that uses the Arduino MQTT library. We will then walk through an example of using the library, setting up and connecting an Arduino Uno board, adding a TMP36 Temperature Sensor.

<iframe width="480" height="270" src="https://www.youtube.com/embed/3kCD5S7N6zE" frameborder="0" allowfullscreen></iframe>

Install Arduino IDE

To use the Cayenne Arduino MQTT Library, the Arduino IDE software should be installed. Go to Arduino IDE to download and install the Arduino IDE software if you need it. Arduino IDE can be installed on Windows, Mac or Linux computers.

Add MQTT Library to Arduino IDE

The Cayenne Arduino MQTT Library is a collection of code, known as sketch files, that makes it easy for you to connect and send data to and from sensors, actuators and devices connected to Arduino boards using MQTT. Cayenne sketch files can be combined with other sketch files for your IoT projects.

The Cayenne Arduino MQTT Library is available directly from the Arduino IDE Libraries list. To install the library, select Sketch > Include library > Manage Libraries. The Library Manager dialog will appear. From here, search for the Cayenne MQTT library and install it.


arduino-ide-manage-libraries


arduino-ide-add-mqtt-library

The Cayenne MQTT library has now been expanded in the libraries folder in your Arduino sketches directory. You can verify this by going to the Sketch > Include Library menu where you should now see the Cayenne MQTT library at the bottom of the drop-down menu under Contributed Libraries. The Cayenne MQTT library is now ready to be used in your project.


arduino-ide-mqtt-library-menu

Configure Arduino IDE

In order to successfully program your Arduino board, you will need to verify that the appropriate Board and Port are selected in the Arduino IDE.

First, verify that the correct Board is selected in the Tools > Board menu. Be sure to select the board type that you will be programming.


Arduino IDE board selection

Then, verify that you have the correct Port selected for communicating with your Arduino. Pick the correct port based upon how you are connecting your Arduino to your PC/Mac.


Arduino IDE port selection

Load the example sketch file

After setting up your PC/Mac computer with the Arduino IDE and the Cayenne MQTT Library, you are ready to proceed with programming your board to connect with Cayenne. The Cayenne MQTT Library comes with several different examples, depending upon which type of connection your Arduino board will use to connect to the Internet. To proceed, we need to load the correct example file for our board.

Open the File > Examples > CayenneMQTT > Connections menu and select the appropriate sketch file example for the connection type you will be using. In our case, we’ll be using the W5100 shield, so we select the EthernetShieldW5100 example. Once selected, the example sketch file will open in the Arduino IDE.

TIP: If you aren’t sure which connection type you have, you can refer to Arduino Ethernet and WiFi Shields for more information.


arduino-ide-connect-example-loaded

Add MQTT Credentials

The example sketch file includes everything we need to connect to Cayenne and publish our first set of test data, but it is missing our unique MQTT credentials that will allow us to connect this device into our account. Let’s add those now.

All of the required information we need can be found on the Cayenne dashboard’s Choose SDK and connect your device screen. Refer to this screen and copy & paste your MQTT Username, MQTT Password and Client ID into the sketch file. The example sketch file includes placeholders for these values, so we just need to update them with the values provided to us on our dashboard.

TIP: The credentials shown here are unique for your account and the current device being added. When programming new devices, always be sure to copy & paste from the Cayenne dashboard screen so that the correct values are used for your device.


Choose SDK and Connect screen


arduino-ide-example-filled-in

Connect board to Cayenne

Once you have double-checked the sketch file, select Sketch > Upload to upload the sketch file to your device. As soon as your Arduino device comes online and connects to Cayenne, your device’s dashboard will appear.


dashboard-1stexperienceb

Congrats! Your hardware is now connected to the Cayenne Cloud!

Send sensor data

Once our board is connected to our Cayenne dashboard, we can send some sensor data and get our very first widget added. For this example, we’ll be using a TMP36 Temperature Sensor. Begin by making sure that your TMP36 sensor is connected to the Arduino board. If you need help connecting this sensor, you can refer to the TMP36 Arduino Tutorial. As in the tutorial, our TMP36 sensor will be connected to the Arduino’s Analog Pin 0.

TIP: You can refer to this example file that includes all of the code used in our example for reading and sending our sensor’s data to Cayenne.

Reading the TMP36 sensor data

The first step in handling our TMP36 sensor is to write some code to read the sensor’s current value. The TMP36 sensor doesn’t give us a Temperature reading, it will give us an output that is related to voltage. We’d prefer to show a temperature in Celsius on our dashboard, so we also need to convert the reading into a usable temperature. We start by adding the code to read and convert the TMP36 from Analog Pin 0 into celsius temperature.

Tip: Refer to the documentation for whatever sensor you are using in order to determine what kind of code needs to be written to read its sensor data.


arduino-ide-tmp36-read-and-convert-sensor

Send Temperature reading to Cayenne

Now let’s send our TMP36 temperature data up to Cayenne. This is easily accomplished, requiring only a single line of code. In this case, we’ll send the data to Cayenne using MQTT Channel 0.

TIP: There are many ways to read and send sensor data. Depending upon what device you are using and what goals you have in mind, you may choose a different way.


arduino-ide-tmp36-send-sensor-data

Once you have double-checked the sketch file, select Sketch > Upload to upload the sketch file to your device. Shortly after our board comes online, it will read the current temperature of our TMP36 sensor and send the reading to Cayenne. Cayenne will receive this data and automatically add a widget for it! Cayenne will do this automatically for any new MQTT data that you send it. Widgets created in this way are temporary by default, giving you an easy way to test sending new data to Cayenne. If you want to keep this widget permanently, simply click on the widget tile and it will become a permanent widget in your dashboard.


dashboard-with-temp-added

Congrats! Your hardware is now sending sensor data to the Cayenne Cloud!

Using mbed MQTT

The Cayenne mbed library will give you everything you need to quickly get your board connected with Cayenne using MQTT and the mbed online IDE, a free online code editor and compiler in which the code is written and compiled within a web browser, and compiled on the cloud using the ARMCC C/C++ compiler.

Example: using the library

In this section we will walk through setting up and connecting a Nucleo board with WiFi shield. After writing code to connect our board, we will demonstrate sending sensor data to our dashboard by sending values from a connected TMP36 Temperature sensor. Finally, we will write code to allow us to control the state of the Nucleo's onboard LED from our dashboard.

To accomplish this goal, we will cover the following topics:

<iframe width="480" height="270" src="https://www.youtube.com/embed/zlQd2RoEQb8" frameborder="0" allowfullscreen></iframe>

TIP: You can also refer to this example project on mbed that includes the code covered in this section for Sending sensor data and Controlling an actuator.

Connect the board

Before you program your board, make sure to connect your board to your computer. Since we are using the Nucleo board, we connect the board to our computer using a USB cable. On Windows, this will automatically download all required drivers and open a shared folder. We will use that shared folder later to upload our compiled binary generated using mbed.


nucleo-shared-folder

Create mbed account

In order to use the mbed IDE you will need to have an account. To get started, visit developer.mbed.org and sign into your account. If you do not already have an account, click on the Log in/Signup link and create an account.


mbed-signup

Once your device is setup and you have your mbed account ready to be used, you may proceed with adding the Cayenne C++ library into mbed.

Setup mbed platform

Before you can program your board, you need setup mbed for the platform that you will be using. If your platform is not already setup, you must do so now.

TIP: If you have been using the mbed IDE for a while, you may already have several platforms setup. Make sure that the correct platform is selected before continuing.

Let’s walk through adding the Nucleo-F446RE to mbed. To begin, visit mbed’s platforms page and select the Nucleo-F446RE there.


mbed-add-plaftorm-1


mbed-add-plaftorm-2-select-nucleo

After selecting your platform, the platform page will appear. Select Add to your mbed Compiler to add this platform. You will see a confirmation that the platform has been added and the mbed IDE will now show this platform available. You can now proceed with Importing the Cayenne C++ library into mbed.


mbed-add-plaftorm-3


mbed-add-plaftorm-4


mbed-add-plaftorm-5-nucleo-platform-added

Import mbed library

The Cayenne mbed Library is a collection of code, support libraries, an MQTT client and example code files designed to help you quickly connect your board to Cayenne using MQTT. There are several versions of the mbed library available and you should select the most appropriate version based upon the board you are using. In our example we’ll be programming a Nucleo board with WiFi shield (F446RE) with the mbed IDE. Cayenne offers an mbed library that supports this board in the mbed IDE, so we will use that library here.

TIP: If Cayenne does not currently your board, toolchain/IDE, or you want more advanced guidance on customizing the Cayenne library, you might wish to check out the Using C++ and Using Embedded C sections which cover more on these topics.

To begin using this library, visit the Cayenne mbed repository which contains a list of the various Cayenne MQTT mbed projects available. For our Nucleo board, we select the Cayenne-X-NUCLEO-IDW01M1 library from the list. This will open a page on mbed from which we can import it into our compiler.


cayenne-mqtt-mbed-libraries

From the Nucleo library page, click on the Import into Compiler button. The Import Program dialog will appear. From this dialog you can give your program a name. We’ll accept the defaults and just click Import to continue.


mbed-import-cayenne-library


mbed-import-cayenne-library2

The Arduino MQTT library has now been imported and mbed has created a new program in our workspace. We can now proceed with examining Cayenne’s example code and customizing it with our WiFi and MQTT Credentials so that we can connect our board to Cayenne.


mbed-library-imported-to-new-program

Add WiFi & MQTT Credentials

With the Arduino MQTT library imported into mbed, we can now examine the example source code and customize it. Since our Nucleo board will connect using WiFi, we will need to specify the WiFi information. We will also need to enter in the required MQTT Credentials that will identify this board and allow it to be connected into our Cayenne account. Without this information, our board will not successfully connect to Cayenne.

Expand the program tree in your mbed workspace and find the example file, main.cpp. Click to open this file in the mbed editor. For our example, the only code that we need to examine & customize is located in this file.


mbed-example-file

Fill in the Wireless network information

The Nucleo board we’ve chosen includes a WiFi network connection, so we will need to program our board so that it can connect to our wireless network. Without this information, our board will be unable to establish proper Internet connectivity and will be unable to communicate with the Cayenne cloud. Refer to the main.cpp file and fill in the SSID and WIFI Password for your wireless connection. The example code includes placeholders for these values, so we just need to update them with the correct information for our wireless network.


mbed-customize-example-code-file-wifi

Fill in the MQTT Credentials

After filling in the network information, we will need to fill in the required MQTT Credentials for our account and this board. Refer to the Choose SDK and connect your device screen on your Cayenne dashboard, copying & pasting your MQTT Username, MQTT Password and Client ID into the example code. The example code includes placeholders for these values as well, so we just need to update them with the values provided to us on our dashboard.

TIP: The credentials shown here are unique for your account and the current device being added. When programming new devices, always be sure to copy & paste from the Cayenne dashboard screen so that the correct values are used for your device.


Choose SDK and Connect screen


mbed-customize-example-code-file-mqtt-creds

Once our program has now been customized, it is ready to be compiled and uploaded to the device so that it can connect to Cayenne.

Connect board to Cayenne

After customizing the example file with the required connection and MQTT Credentials, we can now proceed with compiling our program, uploading it to our board and connecting it to the Cayenne cloud.

To compile our program, click on the Compile button in mbed. Your program will be compiled and mbed will automatically download the compiled binary to your computer. Drag & drop this binary file to your board’s shared folder to upload it to the board.


mbed-compile-complete


mbed-drag-n-drop-binary

After you drag & drop the binary into the device, the Nucleo board will automatically run it. As soon as your device comes online and connects to Cayenne, your device’s dashboard will appear.

TIP: Not all boards will automatically run the binary file. Be sure to read the documentation for your board to see if additional actions are necessary.


dashboard-1stexperienceb

Congrats! Your hardware is now connected to the Cayenne Cloud!

Send sensor data

Once our board is connected to our Cayenne dashboard, we can send some sensor data and get our very first widget added. For this example, we’ll be using a TMP36 Temperature Sensor. Begin by making sure that your sensor is connected to the board.

TIP: There are many ways to read and send sensor data, we’re only showing you one such example here. Depending upon what device you are using and what goals you have in mind, you may choose a very different way. As a reminder, you can refer to this example project on mbed that includes the code mentioned in this section.

Import the TMP36 library

In order to use a TMP36 sensor with mbed, we will import a library that will support reading data from this sensor and converting its readings into temperature readings. There are many such options for sensor libraries in mbed, you may choose a different library than we do for this example.

To import our sensor library, click on the Import button in mbed. From the Libraries screen that appears, you can use the Search field to find appropriate libraries.


mbed-import-sensor-library


mbed-import-library-search

TIP: the mbed site (outside of the compiler screen) also includes a search function that can be used to find libraries. One advantage of using this search is that you can also find more information and discussions on using libraries. You may wish to combine both searches to find what you’re looking for!


mbed-search

To save time, you may use the following direct link to the TMP36 library we'll be using. Clicking on the library link will open a direct page for the library where you can then click Import into Compiler button which will import the TMP36 library and its code into your program’s workspace. Once you have the library imported, you can continue with writing code that makes use of this library to read your sensor’s data.


mbed-import-tmp36-library-completed

Reading the TMP36 sensor data

Now that we have a library that we can use with our sensor, we can write some code that will read its value using that library. We will write this code in the main.cpp file. If you use a different library, or different sensors, be sure to refer to the instructions that come with them for details, including what code you must include for reading data from the sensor.

At a high level, for the library we'll be using, we implement the following tasks in our code for reading from our sensors:

  1. Include the TMP36 header for our library.


    mbed-sensor-step-1

  2. Initialize a TMP36 object from our library with the correct Pin information based on how we connected our sensor.

    The TMP36 library that we're using provides a TMP36 class that includes easy to use functions for reading from our sensor. We create an instance by telling it which pin our sensor is connected to. For this example, our sensor is connected to Pin 5.


    mbed-sensor-step-2

  3. Read the sensor's value using the TMP36 object.

    The TMP36 library makes reading our sensors value very easy. With a single call, the library will read the sensor's value and convert it into a temperature in Celsius for us.


    tmp 36 read sensor value

TIP: To get more of a background on how Publishing sensor data to Cayenne works, you may wish to check out the Manually Publishing / Subscribing section which covers this topic in detail.

Send Temperature reading to Cayenne

Once we’ve implemented reading our sensor’s value in our code, we can continue with sending our sensor’s data up to Cayenne. This is easily accomplished with a single publish function call provided by the library. Since our sensor is connected to Pin 5, we'll publish the data to MQTT on Channel 5.


send sensor value

Once you have written code to handle the TMP36, click on the Compile button and download the binary file from mbed. Drag & drop the updated binary file to your device’s folder. Even though we already have a binary file in place in our Nucleo board’s folder, that won’t matter. The Nucleo board will use the newest binary, removing the old file already there. Shortly after placing the updated binary in the shared folder, the Nucleo board will run the program.

Once our board comes online, it will read the current sensor data from our TMP36 sensor and send the readings to Cayenne. Cayenne will receive this data and automatically add a widget for it! Cayenne will do this automatically for any new MQTT data that you send it. Widgets created in this way are temporary by default, giving you an easy way to test sending new data to Cayenne. If you want to keep this widget permanently, simply click on the widget tile and it will become a permanent widget in your dashboard.


cwalkthrough-dashboard-with-temp-widget

Congrats! Your hardware is now sending sensor data to the Cayenne Cloud!

Control a Light actuator

Now that we have our board connected to Cayenne and it has successfully sent test data to our dashboard, let’s take a look at how easy it is to add an actuator. The Nucleo board includes an onboard LED already. Let’s make use of this and create a Button widget on our dashboard that will let us turn this light ON/OFF.

TIP: Although we’ll be using the Nucleo’s onboard light, the method of adding an additional external actuator is the same as what’s shown here for our Nucleo board. Every board type is different however. Refer to the documentation and code examples for your specific board to see how to program specifically for it.

In order for Cayenne to be able to control the Nucleo’s onboard light, we must perform the following tasks:

  1. Create a dashboard widget that can be used to change its state (e.g. ON/OFF).
  2. Write code so that our actuator changes state when Cayenne tells us it was changed from the dashboard.

TIP: To get more of a background on how Subscribing to actuator data on Cayenne works, you may wish to check out the Manually Publishing / Subscribing section which covers this topic in detail.

Add dashboard widget

Click Add New > Device / Widget.


Add New menu

  1. Choose Custom Widget > Button.

  2. Give your actuator a name, for example enter “Light” into the Name field.

  3. We’ll be adding this actuator to our new Arduino device, so make sure your device is selected in the Device field.

  4. On the Nucleo board, the onboard LED1 is controlled using Pin 0, so select 0 from the Channel field. We would want to make sure the Channel we use here matches what we put in our code later - in the case of the first onboard LED (LED1), this choice is made for us (it’s always pin 0).

    TIP: Be sure to refer to the code that you write to make sure that the Channel you select for your widget matches what you use in code.

  5. We can specify an Icon for our actuator. We’re using it to control a Light, so let’s select a Light icon here.

  6. Click the Step 2: Add Actuator button. The light widget will then be added to our dashboard.


dashboard-add-actuator

Write code for the actuator

Cayenne is now setup to send COMMAND events to our actuator, but nobody is listening. We now need to write code so that our board will listen for Cayenne to inform us when the actuator’s state was changed on the dashboard, and to appropriate change its state.

At a high level, we must implement the following coding tasks:

  1. Add an LED1 object to our code so that we can control it.


    mbed-actuator-step-1

  2. Subscribe to the COMMAND messages that Cayenne sends to our LED.

    TIP: Using the Nucleo library, this task is automatically handled for us! There’s no need for us to subscribe to Command topics.

  3. Change the LED’s state based on what Cayenne tells us the new state is.


    set LED state

  4. Publish the updated LED state to Cayenne dashboard.

Note: This ensures that the correct state for our actuator is reflected on the dashboard.


mbed-actuator-inform-dashboard-of-led-state-zoom

  1. Inform Cayenne that the actuator state change has been handled without errors.


    mbed-actuator-publish-response-zoom

TIP: As a reminder, you can refer to this example project on mbed that includes the code mentioned in this section.

Once you have written code to handle the actuator, click on the Compile button and download the binary file from mbed. Drag & drop the updated binary file to your device’s folder. Even though we already have a binary file in place in our Nucleo board’s folder, that won’t matter. The Nucleo board will use the newest binary, removing the old file already there. Shortly after placing the updated binary in the shared folder, the Nucleo board will run the program. As soon as your board comes online, you can use the dashboard to interact with your actuator.


dashboard-with-test-widgets

Congrats! You can now use the button to control the status of the onboard LED.

Using C++

The Cayenne C++ library will give you everything you need to quickly get your board connected with Cayenne using MQTT and the C++ language. You can find this library and the example code presented in this section in our Cayenne C++ Github repository.

NOTE: There are many different ways to implement your project using the C++ library. The details of this section are written for a more advanced user who is looking for examples on how to extend one of the Cayenne base libraries to support their board. You may also wish to also review the mbed MQTT Library example which provides additional specifics by implementing some of the concepts provided here with specific hardware.

Example: using the library

In this section we will walk through setting up and connecting a Raspberry Pi 3 Model B to Cayenne using MQTT. Since this is a Raspberry Pi device that uses the Linux OS, we will make use of a Linux-based compiler. We will cover topics related to extending the C++ library to support our board on Linux. After covering supporting and connecting our board to our Cayenne dashboard, we will demonstrate sending example sensor data to our dashboard. Finally, we will examine code that handles reacting to a user changing the status of an example Light actuator widget on our dashboard.

To accomplish this goal, we will cover the following topics:

Connect the board

For our example we will use a Raspberry Pi 3. We recommend that you install the Raspbian OS onto your Pi. Raspbian comes with the GNU compiler, making it easy for us to write code for our project.

  1. Power on your Raspberry Pi. Connect the power adapter to your Raspberry Pi.

  2. Connect the Pi to the Internet. Connect your Raspberry Pi to the Internet using an Ethernet cable. Or, if you have a Wi-Fi dongle setup already, this works too.

  3. Make sure the Raspbian operating system is installed. Cayenne works with Jessie OS versions of Raspbian. Please make sure one of these is pre-installed to the sd card. If you need to install the Raspbian operating system, click here.


    Raspberry Pi

Install compiler

If you are using the recommended Raspbian OS, the GNU compiler will already be installed. You can verify this by checking the version.

gcc -v

If your compiler is not yet installed and you are using a Debian distribution, you can easily get all the packages you need by installing the build-essential package.

apt-get install build-essential

After verifying that your compiler is ready to be used, you can move on to installing the Cayenne C++ library.

Install C++ library

The Cayenne C++ library and its examples can be found on our Github repository. To make use of the library, make a clone of the library repository in your project workspace.

For example, to clone the C++ library into a new project called CayenneMQTTTest:

mkdir CayenneMQTTTest
cd CayenneMQTTTest
git clone https://github.com/myDevicesIoT/Cayenne-MQTT-CPP.git

Writing code to support your board/platform

The C++ library bundles all of the basic code needed to connect to Cayenne using MQTT, including the Eclipse Paho MQTT client. In order to operate successfully, the MQTT code requires an implementation of Timer and Networking code that will work for your platform. In addition, you may find it necessary to account for the idiosyncrasies of the specific board that you need to support. This section will help guide you in writing code to support your platform/board.

Implement support for your platform/board

At a mimimum, you must implement the needed Timer and Networking functions that are used by Cayenne's MQTT code. Without these implemented for your platform, networking will not work and the library code will not be able to Publish or Subscribe data to the Cayenne Cloud.

Linux Example

Currently, the C++ library includes a working example for the Linux Operating System. You can find this implementation under the Platform/Linux subfolder in the library files. If you are using a Linux based device, you can use the Linux code we've provided as-is.

Supporting other platforms

Although the Cayenne library includes some working implementation for certain platforms, the library may not include support for the platform that you wish to use. In such instances, you will need to accomplish the following tasks to support your platform:

  1. Implement Networking code, used by the library for connectivity.
  2. Implement Timer code, used by the library for countdown timing.
  3. Pass your Networking & Timer classes as template parameters to the MQTTClient class.

TIP: Even if you may not be using one of the platforms included as examples with the library, you can use the examples as reference when implementing support for your platform. For the remainder of this documentation we will refer back to the Linux example files included with the library as we discuss what the Cayenne team implemented in order to support this platform.

Implementing Networking code

In order for the C++ library and its MQTT client to have proper connectivity, you will need to provide a Network implementation that can be used. This code is needed, for example, to create a tcp connection and provide read/write functions so that the code can connect to the Cayenne Cloud. Because the code needed for this is platform dependent, you will need to provide a working implementation for your platform. We have documented this process in the NetworkInterface include file. In addition, you can refer to the example Linux implementation included with the library.

After implementing your network code, be sure to pass your Network class to the MQTT Client as a templated paramater. You can find an example of this in the Linux platform examples. The MQTT client used by the library will not function without a working networking implementation for your platform.

Implementing Timer code

In order for the C++ library and its MQTT client to handle countdown timing, you will need to provide a Timer implementation that can be used. For example, this code is used for countdown timers, e.g. when to ping, when to timeout of a call. Because the code needed for this is platform dependent, you will need to provide a working implementation for your platform. We have documented this process in the NetworkInterface include file. In addition, you can refer to the example Linux implementation included with the library.

After implementing your timer code, be sure to pass your Timer class to the MQTT Client as a templated paramater. You can find an example of this in the Linux platform examples. The MQTT client used by the library will not function without a working timer implementation for your platform.

Code examples

If you are using a Linux-based board, the C++ library includes working examples for connecting your board, publishing data and subscribing to data from Cayenne. In the next few sections we will discuss these examples and give you some details on how the code uses MQTT to accomplish these tasks.

Exploring the examples

The C++ library includes three helpful examples located in the Platform/Linux examples folder. In the next few sections we will walk through portions of these examples and use them to cover the following concepts:

Examples included in the Linux platform code:

  • SimplePublish - Provides an example of connecting to Cayenne and Publishing dummy sensor data. Cayenne will automatically create dashboard Widgets for sensor data received in this manner.
  • SimpleSubscribe - Provides an example of Subscribing to MQTT topics, demonstrating how to listen for changes to your connected devices issued from the Cayenne dashboard.
  • CayenneClient - An all inclusive example that performs both sending and receiving example data using the Cayenne Cloud.

TIP: To get more of a background on the raw MQTT calls that the libraries use for interacting with Cayenne, as well as a walkthrough of performing each step manually via an MQTT client, you may wish to check out the Manually Publishing / Subscribing section which covers this topic in detail.

Connect board to Cayenne

The first step in verifying that your board is communicating and working with Cayenne is to establish a connection. The SimplePublish example provides the easiest example of doing so. You can find this example in Platform/Linux/Examples folder included with the library. It includes a complete example of connecting to the Cayenne Cloud and sending some simple test data to verify the connection is working. We will use this example for demonstrating connecting your board to Cayenne.

Adding your MQTT Credentials

In order for your MQTT connection to be successful, you must fill in the required MQTT Credentials for our account and this board. Refer to the Choose SDK and connect your device screen on your Cayenne dashboard, copying & pasting your MQTT Username, MQTT Password and Client ID into the example code provided in SimplePublish.cpp. The example code includes placeholders for these values as well, so we just need to update them with the values provided to us on our dashboard.

TIP: The credentials shown here are unique for your account and the current device being added. When programming new devices, always be sure to copy & paste values from your dashboard so that the correct values are used for your device.


Choose SDK and Connect screen


Add your MQTT credentials

Compile, Upload and connect to Cayenne

After filling in your MQTT credentials into the code example, we are ready to run the SimplePublish example. The C++ library includes a Makefile for building the examples. To use the Makefile, navigate to this file in source and run the make command. You can then run the SimplePublish program. As soon as your device comes online and connects to Cayenne, the Choose SDK and connect your device screen will switch automatically to display your device's dashboard.


dashboard-1stexperienceb

Congrats! Your hardware is now connected to the Cayenne Cloud!

Send sensor data to Cayenne

Once our board is connected to our Cayenne dashboard, we can send some test data and get our very first widget added. For this example, we can continue to refer to the SimplePublish example. In addition to connecting to our dashboard, this example also includes two examples of publishing test data to our dashboard.


publish data

Once our board comes online, it will send two test data points to our dashboard, a temperature value and a luminosity value. As soon as Cayenne receives this data, it will automatically add widgets for them! Cayenne will do this automatically for any new MQTT data that you send it. Widgets created in this way are temporary by default, giving you an easy way to test sending new data to Cayenne. If you want to keep this widget permanently, simply click on the widget tile and it will become a permanent widget in your dashboard.


embedded-c-dashboard-simple-publish

Congrats! Your hardware is now sending sensor data to the Cayenne Cloud!

Respond to actuator commands

Now that we have our board connected to Cayenne and it has successfully sent test data to our dashboard, let’s take a look at how easy it is to add an actuator. When users change the state of actuators using the dashboard widgets, Cayenne publishes COMMAND messages. By subscring to these messages, we will be informed when our actuator's state was changed. We can then take action in response, such as telling a connected Light to turn on or off.

For this example, we will setup a Button widget on our dashboard and use it to send actuator commands to an imaginary actuator connected to our board. We will then take a look at the SimpleSubscribe code example that subscribes to data from Cayenne so that we know when our actuator's state was changed on the dashboard.

Add dashboard widget

Let's start by adding a Button widget on the dashboard. From the Cayenne dashboard, click Add New > Device / Widget.


Add New menu

  1. Choose Custom Widget > Button.
  2. Give your actuator a name, for example enter “Light” into the Name field.
  3. We’ll be adding this actuator to our custom device, so make sure your device is selected in the Device field.
  4. Select 0 from the Channel field.

Note: The SimpleSubscribe code doesn't care what channel our device is connected to, but normally we would want to make sure the Channel selected here matches up with the channel that our code uses later when watching for COMMAND messages sent from Cayenne. Our recommendation is to stick to using Channel == the Pin your actuator is connected to.

  1. We can specify an Icon for our actuator. Say we’re using it to control a Light, so let’s select a Light icon here.
  2. Click the Step 2: Add Actuator button. The light widget will then be added to our dashboard.


Dashboard settings - add actuator

Write code for the actuator

To properly handle actuator commands with Cayenne, it first helps to understand a bit about how Cayenne expects a well behaved client to react to actuator commands. Cayenne expects a client to:

  1. Subscribe to COMMAND messages from Cayenne.

  2. When a new COMMAND arrives, handle changing the status of the actuator connected to the board.

    Note: Cayenne will inform the listener which Channel was effected as well as what the new state is.

  3. After changing (or attempting) to change the actuator state, inform Cayenne what the current status now is.

    Note: It's very important to inform Cayenne what the correct state is. This ensures that the dashboard properly reflects the correct current state of the device.

  4. Inform Cayenne whether the event was handled OK or had an Error.

    Note: If there was an error, Cayenne will handle showing the error to the user so that they're aware of it.

With that background in place, let's discuss how to implement these tasks in code. The SimpleSubscribe example provides provides an example of dealing with COMMAND messages from Cayenne. You can find this example in Platform/Linux/Examples folder included with the library. It includes code to listen and react to all COMMAND messages received from Cayenne, making it easy for us to quickly test an example of controlling an actuator with the dashboard.

Note: The SimpleSubscribe example handles messages received from Cayenne by simplying responding back that the state was successfully changed. In order to be useful in your program, you will want to also make sure your code makes changes to your actuator's physical state. The code for accomplishing this is left for you to write for your device, just be sure to do so!

TIP: If you want more details beyond the sample code provided with the library, the Manually Publishing / Subscribing - Actuator's section also covers these steps in more detail.

Adding your MQTT Credentials

As before with the SimplePublish example, we need to fill in our MQTT Credentials into the code for the SimpleSubscribe example code. If we fail to do so, our device will not be able to connect to our account.

TIP: If you ever need to refer to the MQTT Credentials needed for operations such as this, you can refer back to the Configuration screen for your board. To do so, select the cogwheel menu for your board and then the Configure option. In the configuration screen that appears, you'll find the values that you need.


api-configure-menu


api-configure-screen


Add your MQTT credentials

Compile, Upload and connect to Cayenne

After filling in your MQTT credentials into the code example, we are ready to run the SimpleSubscribe example. The C++ library includes a Makefile for building the examples. To use the Makefile, navigate to this file in source and run the make command. You can then run the SimpleSubscribe program. As soon as your device comes online and connects to Cayenne, you can use the Button widget on the dashboard, triggering actuator COMMAND messages to be sent to your board. The SimpleSubscribe code will handle these messages by replying back to our dashboard that the actuator was successfully changed and our dashboard will update to show the changed state.


embedded-c-dashboard-simple-subscribe

Congrats! You can now use the button to send actuator commands to your board.

Using Embedded C

The Cayenne Embedded C library will give you everything you need to quickly get your board connected with Cayenne using MQTT and the C language. You can find this library and the example code presented in this section in our Cayenne Embedded C Github repository.

NOTE: There are many different ways to implement your project using the C library. The details of this section are written for a more advanced user who is looking for examples on how to extend one of the Cayenne base libraries to support their board. You may also wish to also review the mbed MQTT Library example which provides additional specifics by implementing some of the concepts provided here with specific hardware.

Example: using the library

In this section we will walk through setting up and connecting a Raspberry Pi 3 Model B to Cayenne using MQTT. Since this is a Raspberry Pi device that uses the Linux OS, we will make use of a Linux-based compiler. We will cover topics related to extending the Embedded C library to support our board on Linux. After covering supporting and connecting our board to our Cayenne dashboard, we will demonstrate sending example sensor data to our dashboard. Finally, we will examine code that handles reacting to a user changing the status of an example Light actuator widget on our dashboard.

To accomplish this goal, we will cover the following topics:

Connect the board

For our example we will use a Raspberry Pi 3. We recommend that you install the Raspbian OS onto your Pi. Raspbian comes with the GNU compiler, making it easy for us to write code for our project.

  1. Power on your Raspberry Pi. Connect the power adapter to your Raspberry Pi.

  2. Connect the Pi to the Internet. Connect your Raspberry Pi to the Internet using an Ethernet cable. Or, if you have a Wi-Fi dongle setup already, this works too.

  3. Make sure the Raspbian operating system is installed. Cayenne works with Jessie OS versions of Raspbian. Please make sure one of these is pre-installed to the sd card. If you need to install the Raspbian operating system, click here.


    Raspberry Pi

Install compiler

If you are using the recommended Raspbian OS, the GNU compiler will already be installed. You can verify this by checking the version.

gcc -v

If your compiler is not yet installed and you are using a Debian distribution, you can easily get all the packages you need by installing the build-essential package.

apt-get install build-essential

After verifying that your compiler is ready to be used, you can move on to installing the Cayenne Embedded C library.

Install Embedded C library

The Cayenne Embedded C library and its examples can be found on our Github repository. To make use of the library, make a clone of the library repository in your project workspace.

For example, to clone the C library into a new project called CayenneMQTTTest:

mkdir CayenneMQTTTest
cd CayenneMQTTTest
git clone https://github.com/myDevicesIoT/Cayenne-MQTT-C.git

Writing code to support your board/platform

The Embedded C library bundles all of the basic code needed to connect to Cayenne using MQTT, including the Eclipse Paho MQTT client. In order to operate successfully, the MQTT code requires an implementation of Timer and Networking code that will work for your platform. In addition, you may find it necessary to account for the idiosyncrasies of the specific board that you need to support. This section will help guide you in writing code to support your platform/board.

Implement support for your platform/board

At a mimimum, you must implement the needed Timer and Networking functions that are used by Cayenne's MQTT code. Without these implemented for your platform, networking will not work and the library code will not be able to Publish or Subscribe data to the Cayenne Cloud.

Linux Example

Currently, the Embedded C library includes a working example for the Linux Operating System. You can find this implementation under the Platform/Linux subfolder in the library files. If you are using a Linux based device, you can use the Linux code we've provided as-is.

Supporting other platforms

Although the Cayenne library includes some working implementation for certain platforms, the library may not include support for the platform that you wish to use. In such instances, you will need to accomplish the following tasks to support your platform:

  1. Implement Networking code, used by the library for connectivity.
  2. Implement Timer code, used by the library for countdown timing.
  3. Update the CayenneMQTTClient/PlatformHeader.h to reference your new Timer, Networking implementation.

TIP: Even if you may not be using one of the platforms included as examples with the library, you can use the examples as reference when implementing support for your platform. For the remainder of this documentation we will refer back to the Linux example files included with the library as we discuss what the Cayenne team implemented in order to support this platform.

Implementing Networking code

In order for the Embedded C library and its MQTT client to have proper connectivity, you will need to provide a Network implementation that can be used. This code is needed, for example, to create a tcp connection and provide read/write functions so that the code can connect to the Cayenne Cloud. Because the code needed for this is platform dependent, you will need to provide a working implementation for your platform. We have documented this process in the PlatformHeader include file. In addition, you can refer to the Linux implementation included with the library.

After implementing your timer code, be sure to then include a link to your file(s) in PlatformHeader.h. The MQTT client used by the library will not function without a working networking implementation for your platform.

Implementing Timer code

In order for the Embedded C library and its MQTT client to have proper connectivity, you will need to provide a Timer implementation that can be used. For example, this code is used for countdown timers, e.g. when to ping, when to timeout of a call. We have documented this process in the PlatformHeader include file. In addition, you can refer to the Linux implementation included with the library.

After implementing your timer code, be sure to then include a link to your file(s) in PlatformHeader.h. The MQTT client used by the library will not function without a working timer implementation for your platform.

Code examples

If you are using a Linux-based board, the Embedded C library includes working examples for connecting your board, publishing data and subscribing to data from Cayenne. In the next few sections we will discuss these examples and give you some details on how the code uses MQTT to accomplish these tasks.

Exploring the examples The Embedded C library includes three helpful examples located in the Platform/Linux examples folder. In the next few sections we will walk through portions of these examples and use them to cover the following concepts:

Examples included in the Linux platform code:

  • SimplePublish - Provides an example of connecting to Cayenne and Publishing dummy sensor data. Cayenne will automatically create dashboard Widgets for sensor data received in this manner.
  • SimpleSubscribe - Provides an example of Subscribing to MQTT topics, demonstrating how to listen for changes to your connected devices issued from the Cayenne dashboard.
  • CayenneClient - An all inclusive example that performs both sending and receiving example data using the Cayenne Cloud.

TIP: To get more of a background on the raw MQTT calls that the libraries use for interacting with Cayenne, as well as a walkthrough of performing each step manually via an MQTT client, you may wish to check out the Manually Publishing / Subscribing section which covers this topic in detail.

Connect board to Cayenne

The first step in verifying that your board is communicating and working with Cayenne is to establish a connection. The SimplePublish example provides the easiest example of doing so. You can find this example in Platform/Linux/Examples folder included with the library. It includes a complete example of connecting to the Cayenne Cloud and sending some simple test data to verify the connection is working. We will use this example for demonstrating connecting your board to Cayenne.

Adding your MQTT Credentials

In order for your MQTT connection to be successful, you must fill in the required MQTT Credentials for our account and this board. Refer to the Choose SDK and connect your device screen on your Cayenne dashboard, copying & pasting your MQTT Username, MQTT Password and Client ID into the example code provided in SimplePublish.c. The example code includes placeholders for these values as well, so we just need to update them with the values provided to us on our dashboard.

TIP: The credentials shown here are unique for your account and the current device being added. When programming new devices, always be sure to copy & paste from the dashboard so that the correct values are used for your device.


Choose SDK and Connect screen


Add your MQTT credentials

Compile, Upload and connect to Cayenne

After filling in your MQTT credentials into the code example, we are ready to run the SimplePublish example. The Embedded C library includes a Makefile for building the examples. To use the Makefile, navigate to this file in source and run the make command. You can then run the SimplePublish program. As soon as your device comes online and connects to Cayenne, the Choose SDK and connect your device screen will switch automatically to display your device's dashboard.


dashboard-1stexperienceb

Congrats! Your hardware is now connected to the Cayenne Cloud!

Send sensor data to Cayenne

Once our board is connected to our Cayenne dashboard, we can send some test data and get our very first widget added. For this example, we can continue to refer to the SimplePublish example. In addition to connecting to our dashboard, this example also includes two examples of publishing test data to our dashboard.


embedded-c-code-publish-data

Once our board comes online, it will send two test data points to our dashboard, a temperature value and a luminosity value. As soon as Cayenne receives this data, it will automatically add widgets for them! Cayenne will do this automatically for any new MQTT data that you send it. Widgets created in this way are temporary by default, giving you an easy way to test sending new data to Cayenne. If you want to keep this widget permanently, simply click on the widget tile and it will become a permanent widget in your dashboard.


embedded-c-dashboard-simple-publish

Congrats! Your hardware is now sending sensor data to the Cayenne Cloud!

Respond to actuator commands

Now that we have our board connected to Cayenne and it has successfully sent test data to our dashboard, let’s take a look at how easy it is to add an actuator. When users change the state of actuators using the dashboard widgets, Cayenne publishes COMMAND messages. By subscring to these messages, we will be informed when our actuator's state was changed. We can then take action in response, such as telling a connected Light to turn on or off.

For this example, we will setup a Button widget on our dashboard and use it to send actuator commands to an imaginary actuator connected to our board. We will then take a look at the SimpleSubscribe code example that subscribes to data from Cayenne so that we know when our actuator's state was changed on the dashboard.

Add dashboard widget

Let's start by adding a Button widget on the dashboard. From the Cayenne dashboard, click Add New > Device / Widget.


Add New menu

  1. Choose Custom Widget > Button.
  2. Give your actuator a name, for example enter “Light” into the Name field.
  3. We’ll be adding this actuator to our custom device, so make sure your device is selected in the Device field.
  4. Select 0 from the Channel field.

Note: The SimpleSubscribe code doesn't care what channel our device is connected to, but normally we would want to make sure the Channel selected here matches up with the channel that our code uses later when watching for COMMAND messages sent from Cayenne. Our recommendation is to stick to using Channel == the Pin your actuator is connected to.

  1. We can specify an Icon for our actuator. Say we’re using it to control a Light, so let’s select a Light icon here.
  2. Click the Step 2: Add Actuator button. The light widget will then be added to our dashboard.


Dashboard settings - add actuator

Write code for the actuator

To properly handle actuator commands with Cayenne, it first helps to understand a bit about how Cayenne expects a well behaved client to react to actuator commands. Cayenne expects a client to:

  1. Subscribe to COMMAND messages from Cayenne.

  2. When a new COMMAND arrives, handle changing the status of the actuator connected to the board.

    Note: Cayenne will inform the listener which Channel was effected as well as what the new state is.

  3. After changing (or attempting) to change the actuator state, inform Cayenne what the current status now is.

    Note: It's very important to inform Cayenne what the correct state is. This ensures that the dashboard properly reflects the correct current state of the device.

  4. Inform Cayenne whether the event was handled OK or had an Error.

    Note: If there was an error, Cayenne will handle showing the error to the user so that they're aware of it.

With that background in place, let's discuss how to implement these tasks in code. The SimpleSubscribe example provides an example of dealing with COMMAND messages from Cayenne. You can find this example in Platform/Linux/Examples folder included with the library. It includes code to listen and react to all COMMAND messages received from Cayenne, making it easy for us to quickly test an example of controlling an actuator with the dashboard.

Note: The SimpleSubscribe example handles messages received from Cayenne by simplying responding back that the state was successfully changed. In order to be useful in your program, you will want to also make sure your code makes changes to your actuator's physical state. The code for accomplishing this is left for you to write for your device, just be sure to do so!

TIP: If you want more details beyond the sample code provided with the library, the Manually Publishing / Subscribing - Actuator's section also covers these steps in more detail.

Adding your MQTT Credentials

As before with the SimplePublish example, we need to fill in our MQTT Credentials into the code for the SimpleSubscribe example code. If we fail to do so, our device will not be able to connect to our account.

TIP: If you ever need to refer to the MQTT Credentials needed for operations such as this, you can refer back to the Configuration screen for your board. To do so, select the cogwheel menu for your board and then the Configure option. In the configuration screen that appears, you'll find the values that you need.


api-configure-menu


api-configure-screen


Add your MQTT credentials

Compile, Upload and connect to Cayenne

After filling in your MQTT credentials into the code example, we are ready to run the SimpleSubscribe example. The Embedded C library includes a Makefile for building the examples. To use the Makefile, navigate to this file in source and run the make command. You can then run the SimpleSubscribe program. As soon as your device comes online and connects to Cayenne, you can use the Button widget on the dashboard, triggering actuator COMMAND messages to be sent to your board. The SimpleSubscribe code will handle these messages by replying back to our dashboard that the actuator was successfully changed and our dashboard will update to show the changed state.


embedded-c-dashboard-simple-subscribe

Congrats! You can now use the button to send actuator commands to your board.

Manually Publishing / Subscribing

This section will walk you through using raw MQTT calls to manually publish and subscribe to the Cayenne Cloud. This can help you test out using MQTT with Cayenne. We will walk through an example of faking a board connecting to Cayenne, publishing temperature data to our dashboard and finally by adding a Light actuator and subscribing to its messages sent by our Cayenne dashboard.

For the purposes of our example we will make use of MQTT.fx, a JavaFX based MQTT client.

Install MQTT.fx

To begin using MQTT.fx, we must download and install it. Doing so is easy and straight forward. Simply visit the MQTT.fx download page. Download and install the correct version for the Operating System that you are using. Once installed, launch the MQTT.fx client to get started.


mqtt-fx-1-initial-launch

Add Connection Profile

In order to connect to the Cayenne Cloud, you will need to setup a Connection Profile in MQTT.fx. To do so, click on the cogwheel icon or select Extras > Edit Connection Profiles from the menu. The Edit Connection Profiles screen appears. From this screen you can enter in all the required information needed to complete a profile for connecting to Cayenne.

TIP: All of the required information we need can be found on the Cayenne dashboard’s 'Choose SDK and connect your device' screen. Refer to this screen and the informaiton below to complete creating your connection profile to Cayenne.


Choose SDK and Connect screen

  1. Give the profile a name, such as CayenneMQTT, in the Profile Name field.
  2. Copy & paste the MQTT Server URL from the dashboard into the Broker Address field.
  3. Leave the Broker Port at its default of 1883.
  4. Copy & paste the CLIENT ID field from the dashboard into the Client ID field.
  5. On the User Credentials tab, copy & paste MQTT Username from the dashboard into the User Name field.
  6. Also on the User Credentials tab, copy & paste MQTT Password from the dashboard into the Password field.
  7. The default values for fields in the other tabs are OK to leave as-is. Click the OK button to save our profile.


mqtt-fx-2-connection-profile

We can now make use of our profile to connect to the Cayenne MQTT server and test out publishing and subscribing to data.

Connect board to Cayenne

Now that our profile is setup, we can connect to Cayenne. To do so, click on the Connect button. This will establish a connection to Cayenne and it will also mimic our board coming online. Switching back to examining our browser, you'll find that the Choose SDK and connect your device screen will disappear and the default dashboard for our device will appear.


mqtt-fx-3-profile-created


mqtt-fx-5-device-dashboard

Congrats! You are now connected to the Cayenne cloud using MQTT.

Send sensor data to Cayenne

Now that we have a connection to the Cayenne MQTT server, let's put our connection to use by simulating sending sensor data to our dashboard. For our example, we will simulate having a Temperature sensor connected by publishing a sensor reading up to our dashboard. To do this, switch to MQTT.fx and make sure the Publish tab is selected. From here we can enter in the MQTT details to publish sample sensor data to Cayenne.

To publish sensor data to Cayenne using MQTT, we refer to the MQTT Messaging Topics - Send sensor data section of the docs. There, we find the details on which MQTT call to make. According to the docs, Sending sensor data expects:

v1/username/things/clientID/data/channel

We then substitute in the values for our account, board and sensor.

  • Replace username with the MQTT Username for your account.
  • Replace clientID with the Client ID for your board.
  • Replace channel with the appropriate channel that this sensor is connected to. For this example, we'll assume that we have a temperature sensor connected and using Channel 0.

TIP: If you ever need to refer to the MQTT Credentials needed for operations such as this, you can refer back to the Configuration screen for your board. To do so, select the cogwheel menu for your board and then the Configure option. In the configuration screen that appears, you'll find the values that you need.


api-configure-menu


api-configure-screen

Next, we need to send some actual data. According to the documentation, we need to send this in the following form:

type,unit=value

The Cayenne documentation provides a complete list of Supported Data Types that can be referred to when you need to know what details to put here. We want to send Temperature data, so we find Temperature in the supported data types section. For our example, let's assume that we want to send our temperature in Celsius. We'll use a sample sensor value, say 20.7 Celsius to be sent to Cayenne. With this in mind, and after examining the chart for the Temperature data type, we determine the following values should be used:

  • Type (Temperature): temp
  • Unit (Celsius): c
  • Value: 20.7


mqtt-fx-8-send-temp-sensor-data

TIP: If you want the Cayenne Cloud to retain the last published value for a sensor, be sure to click on the Retained button in MQTT.fx. Without this, you may find that your widget disappears when you refresh the page.

After entering in the MQTT details for publishing our sample sensor data, click on the Publish button to send the data to Cayenne. Cayenne will receive this data and automatically add a widget for it! Cayenne will do this automatically for any new MQTT data that you send it. Widgets created in this way are temporary by default, giving you an easy way to test sending new data to Cayenne. If you want to keep this widget permanently, simply click on the widget tile and it will become a permanent widget in your dashboard.


mqtt-fx-9-temp-widget-created

Congrats! You are now sending data to the Cayenne Cloud!

Control a Light actuator

Now that we have our connection to Cayenne and successfully sent test data to our dashboard, let’s take a look at how easy it is to add an actuator. When users change the state of actuators using the dashboard widgets, Cayenne publishes COMMAND messages. By subscring to these messages, you will be informed when our actuator's state was changed.

For this example, we will setup a Button widget on our dashboard and use it to send actuator commands to an imaginary actuator connected to our board. In doing so, we will also cover the steps that Cayenne expects well behaved clients to perform when interacting with actuators via MQTT.

Add dashboard widget

Let's start by adding a Button widget on the dashboard. From the Cayenne dashboard, click Add New > Device / Widget.


Add New menu

  1. Choose Custom Widget > Button.
  2. Give your actuator a name, for example enter “Test Light” into the Name field.
  3. We’ll be adding this actuator to our custom device, so make sure your device is selected in the Device field.
  4. Select 1 from the Channel field.
  5. We can specify an Icon for our actuator. Say we’re using it to control a Light, so let’s select a Light icon here.
  6. Click the Step 2: Add Actuator button. The light widget will then be added to our dashboard.


mqtt-fx-10-actuator-settings


actuator off

Testing the actuator

In order to test out our actuator, it first helps to understand a bit about how Cayenne expects a well behaved client to react to actuator commands. Cayenne expects a client to:

  1. Subscribe to COMMAND messages from Cayenne.

  2. When a new COMMAND arrives, handle changing the status of the actuator connected to the board.

    Note: Cayenne will inform the listener which Channel was effected as well as what the new state is.

  3. After changing (or attempting) to change the actuator state, inform Cayenne what the current status now is.

    Note: It's very important to inform Cayenne what the correct state is. This ensures that the dashboard properly reflects the correct current state of the device.

  4. Inform Cayenne whether the event was handled OK or had an Error.

    Note: If there was an error, Cayenne will handle showing the error to the user so that they're aware of it.

With that background in place, let's go over performing each of these steps using MQTT.fx.

Receive Actuator command

In order to receive the COMMAND messages that Cayenne sends for changes to our actuator, we must first Subscribe to them. To subscribe to actuator command messages, we refer to the MQTT Messaging Topics - Receive actuator command section of the docs. There, we find the details on what MQTT call to make. According to the docs, Subscribing to actuator commands expects:

v1/username/things/clientID/cmd/channel

We then substitute in the values for our account, board and actuator.

  • Replace username with the MQTT Username for your account.
  • Replace clientID with the Client ID for your board.
  • Replace channel with the appropriate channel that this actuator is connected to. For this example, we've already chosen Channel 1 when our Light actuator widget was setup.

TIP: For the purposes of testing with MQTT, you could also use the wildcard # which would subscribe to all channels. Cayenne supports all of the usually filtering and control from MQTT that you'd expect. But since we know the specific Channel that we want to subscribe to in our example, we'll use that.


mqtt-fx-11-subscribe-command-messages

After entering in the details needed to subscribe to the Command messages for our actuator, click on the Publish button in MQTT.fx. We are now subscribed to the COMMAND messages that Cayenne sends when our actuator state is changed.

Send Actuator Updated Value

Now that we'll be notified when our actuator's state is changed on the dashboard, let's try it out. Using the Cayenne dashboard, click on the Button for your Light actuator. Cayenne publishes a COMMAND message and the dashboard widget will enter a Waiting state as it awaits confirmation that the actuator's state was changed.


actuator waiting

Examining MQTT.fx, we can see the Command message arrive from Cayenne. The message from Cayenne includes two parts:

  1. A Sequence identifier. This is a randomly generated string that is used by the Cayenne Cloud to tie which widget this command is associated with. Keep this value in mind for now as we will need this identifier in the next step when we send a command response back to Cayenne.

  2. A Value. This indicates what the new value of the actuator should be. In the case of our Light actuator, Cayenne is informing us that the new state should be 1 - "On".


mqtt-fx-12b-command-message-from-cayenne

Note: Normally, at this point we would handle actually changing the state of our actuator. For example, our code would interact with the actuator and change its state. Since we're just faking some data, there's nothing for us to actually change, but we do need to inform Cayenne that the actuator's state was changed. We do so by sending a value to Cayenne for what the new state is. Cayenne wanted us to turn on the Light, so let's simply tell Cayenne that's what happened.

To tell Cayenne what the updated value is, we refer to the Send Actuator Updated Value section of the docs. There, we find the details on what MQTT call to make. According to the docs, Cayenne expects:

v1/username/things/clientID/data/channel

Once again, we then substitute in the values for our account, board and actuator.

  • Replace username with the MQTT Username for your account.
  • Replace clientID with the Client ID for your board.
  • Replace channel with the appropriate channel that this actuator is connected to. For this example, we chose Channel 1 for our Light actuator.

Next, we need to inform Cayenne what the actual value for our actuator is. Cayenne asked for the new status to be 1 (meaning On), so we'll give it the value of 1.

Note: Be sure to inform Cayenne what the actual status of the actuator is. For example, if changing the actuator state failed, be sure to tell Cayenne what the correct current value is. Cayenne needs to receive the current value so that the dashboard correctly informs the user what the actual state of their device is.


mqtt-fx-13-inform-cayenne-actuator-state

Once the dashboard receives an updated value for the widget, our Light actuator switches out of the Waiting state and now reflects the fact that our Light is On.


actuator on

Send command response

The final step in completing our actuator change is to inform Cayenne as to whether the actuator state change was handled OK, or if there was a problem. This gives Cayenne an opportunity to display an error message to the user if needed. To send this to Cayenne, we use the Send Command response call. Examining the docs for this call, we see Cayenne expects:

v1/username/things/clientID/response

Once again, we then substitute in the values for our account and board.

  • Replace username with the MQTT Username for your account.
  • Replace clientID with the Client ID for your board.

Next, we need to tell Cayenne if there was an error or if things were handled OK. According to the docs, we need to send this in one of the following forms (depending on OK vs Error):

ok,seq
error,seq=message

We're using a make believe actuator, so changing our actuator's state can't fail. So in this case let's just tell Cayenene that everything was handled without incident. We need to provide the following two pieces of information for this:

  1. The string Value "ok". This lets Cayenne know things were handled OK, no errors to display to the user on the dashboard.

  2. The Sequence identifier. If you'll recall, this value was provided to us when we received the COMMAND message from Cayenne. We provide it here so that Cayenne knows what we're responding to.

Click on the Publish button to send the command response to Cayenne. If you send an error message, Cayenne will display it in the dashboard.


mqtt-fx-14-response-to-cayenne

Congrats! You can now handle actuator messages sent by the Cayenne Cloud!

Supported Data Types

In order to process data appropriately, Cayenne needs to know both data type and unit. This can be configured from the dashboard or directly set when sending data. Despite setting type and unit are optional when sending data, doing that will allow to automatically configure the dashboard as soon as data is received.

Actuators

Data Type Type Constant & Value Unit Unit Constant & Value Widgets
Analog Actuator ANALOG_ACTUATOR analog_actuator Analog ANALOG null Slider
Digital Actuator DIGITAL_ACTUATOR digital_actuator Digital (0/1) DIGITAL null Button
HVAC.Change State HVAC_CHANGE_STATE hvac_state State User defined null HVAC (coming Soon), Slider
HVAC.Change Temperature HVAC_CHANGE_TEMP hvac_temp Fahrenheit FAHRENHEIT f HVAC (coming Soon), Slider
\* Celsius CELSIUS c
HVAC.Off/On HVAC_OFF_ON hvac_off_on Off/On OFF_ON null HVAC (coming Soon), Button
Light Switch LIGHT_SWITCH_ACT lt_switch_act \* Off/On OFF_ON null Lighting (coming soon), Button, Switch (coming soon)
Digital (0/1) DIGITAL d
Low/High LOW_HIGH null
Lighting.Color LIGHTING_COLOR lt_color Hexadecimal HEX null Lighting (coming soon), Slider
Lighting.Luminosity LIGHTING_LUMINOSITY lt_lum \* % (0 to 100) PERCENT p Lighting (coming soon), Slider
Lux LUX lux
Volts VOLTS v
Ratio RATIO r
Motor MOTOR motor \* Off/On OFF_ON null Button, Slider, Switch (coming soon)
Low/High LOW_HIGH null
Degree Angle DEGREE deg
Relay RELAY relay \* Off/On OFF_ON null Button
Low/High LOW_HIGH null
Switch SWITCH switch \* Off/On OFF_ON null Switch (coming soon), Button
Low/High LOW_HIGH null
Digital (0/1) DIGITAL d
Valve VALVE valve \* Off/On OFF_ON null Switch (coming soon), Button
Low/High LOW_HIGH null
Digital (0/1) DIGITAL d

Sensors

Data Type Type Constant & Value Unit Unit Constant & Value Widgets
Digital Sensor DIGITAL_SENSOR digital_sensor Digital (0/1) DIGITAL d 2 State
Analog Sensor ANALOG_SENSOR analog_sensor Analog ANALOG null Value, Line Chart, Gauge
Absolute Humidity ABSOLUTE_HUMIDITY abs_hum Grams per cubic meter GRAMS_PER_METER3 gm3 Gauge, Line Chart, Value
Absorbed Radiation ABSORBED_RADIATION absrb_rad \* Rad RAD rad Line Chart, Gauge, Value
Gray GRAY gy
Acceleration.gx axis ACCELERATION_GX gx Meters per second squared METER_PER_SEC_SQ ms2 Accelerometer (coming soon), Line Chart, Gauge, Value
Acceleration.gy axis ACCELERATION_GY gy Meters per second squared METER_PER_SEC_SQ ms2 Accelerometer (coming soon), Line Chart, Gauge, Value
Acceleration.gz axis ACCELERATION_GZ gz Meters per second squared METER_PER_SEC_SQ ms2 Accelerometer (coming soon), Line Chart, Gauge, Value
Altitude ALTITUDE alt \* Meters above sea level METER m Line Chart, Gauge, Value
Feet above sea level FEET ft
Amount of substance AMOUNT_SUBSTANCE amount Mole MOLE mol Line Chart, Gauge, Value
Area AREA area Square meter METER2 m2 Line Chart, Gauge, Value
Barometric pressure BAROMETRIC_PRESSURE bp Pascal PASCAL pa Line Chart, Gauge, Value
\* Hecto Pascal HECTOPASCAL hpa
Battery BATTERY batt \* % (0 to 100) PERCENT p Gauge, Line Chart, Value
Ratio RATIO r
Volts VOLTS v
Biometric BIOMETRIC bio Byte Array BYTE_ARRAY null Line Chart, Gauge, Value, 2 State
Blood Count BLOOD blood \* Cells by cubic millimeter CELLS_MM3 cmm Line Chart, Gauge, Value
% (0 to 100) PERCENT p
Bytes BYTES bytes Bits BIT bit Value, Gauge, Line Chart
\* Bytes BYTE byte
Kilobytes KB_BYTE kb
Megabytes MB_BYTE mb
Gigabytes GB_BYTE gb
Terabytes TB_BYTE tb
Capacitance CAPACITANCE cap Farad FARAD farad Line Chart, Gauge, Value
Carbon Dioxide CO2 co2 \* Parts per milliion PPM ppm CO2 Detector (coming soon), Line Chart, Gauge, Value
Units of Micromole UNITS_MICROMOLE wmoco2
Charge CHARGE charge Coulomb COULOMB q Line Chart, Gauge, Value
Cholesterol CHOLESTEROL chol Millimoles/liter MMOL_L mmol Line Chart, Gauge, Value
\* Milligrams/deciliter MG_DL mgdl
Color COLOR color \* RGB RGB null Line Chart, Gauge, Value
CYMK CYMK null
Hexadecimal HEX null
Conductance CONDUCTANCE conduct Siemen SIEMEN s Line Chart, Gauge, Value
Counter COUNTER counter Analog ANALOG null Value, Line Chart, Gauge
CPU CPU cpu % (0 to 100) PERCENT p Gauge, Line Chart, Value
Current CURRENT current Ampere AMP a Line Chart, Gauge, Value
Current density CURRENT_DENSITY current_density Ampere per squre meter AMP_2_METER am2 Line Chart, Gauge, Value
Density DENSITY density Kilograms per cubic meter KGM3 kgm3 Line Chart, Gauge, Value
Effective Radiation EFFECTIVE_RADATION eff_rad Roentgen ROENTGEN roent Line Chart, Gauge, Value
Sievert SIEVERT sv
SieVert per Hour SIEVERT_HOUR svph
Energy ENERGY energy Killowatts per hour KW_PER_H kwh Line Chart, Gauge, Value
External Waterleak EXT_WATERLEAK ext_wleak Analog ANALOG null Gauge, Line Chart, Value
Force FORCE force \* Newtons NEWTON null Line Chart, Gauge, Value
Metric METRIC_FORCE force
Frequency FREQUENCY freq Hertz HERTZ hz Line Chart, Gauge, Value
Gas GAS gas \* Pascal PASCAL pa Line Chart, Gauge, Value
Cubic meters METER3 m3
Kilograms per cubic meter KGM3 kgm3
Glucose GLUCOSE glucose Millimoles/liter MMOL_L mmol Line Chart, Gauge, Value
\* Milligrams/deciliter MG_DL mgdl
GPS GPS gps \* Global Positioning System GPS gps Map
Universal Transverse Mercator UTM utm
Gravity.x axis GRAVITY_X grav_x Newtons per kilogram NEWTON_PER_KG nkg Gravity (coming soon), Donut (coming soon), Line Chart, Gauge, Value
\* Meters per second squared METER_PER_SEC_SQ ms2
Gravity.y axis GRAVITY_Y grav_y Newtons per kilogram NEWTON_PER_KG nkg Gravity (coming soon), Donut (coming soon), Line Chart, Gauge, Value
\* Meters per second squared METER_PER_SEC_SQ ms2
Gravity.z axis GRAVITY_Z grav_z Newtons per kilogram NEWTON_PER_KG nkg Gravity (coming soon), Donut (coming soon), Line Chart, Gauge, Value
\* Meters per second squared METER_PER_SEC_SQ ms2
Gyroscope.rate of rotation around x axis GYRO_X gyro_x \* Rotation speed ROTATION rot Gyroscope (coming soon), Line Chart, Gauge, Value
Meters per second squared METER_PER_SEC_SQ mps2
Gyroscope.rate of rotation around y axis GYRO_Y gyro_y \* Rotation speed ROTATION rot Gyroscope (coming soon), Line Chart, Gauge, Value
Meters per second squared METER_PER_SEC_SQ mps2
Gyroscope.rate of rotation around z axis GYRO_Z gyro_z \* Rotation speed ROTATION rot Gyroscope (coming soon), Line Chart, Gauge, Value
Meters per second squared METER_PER_SEC_SQ mps2
HVAC.Humdity HVAC_HUMIDITY hvac_hum % (0 to 100) PERCENT p HVAC (coming soon), Gauge, Line Chart, Value
Image IMAGE image Byte Array BYTE_ARRAY null Camera (Gallery)(coming soon)
Impedance IMPEDANCE imped Ohm OHM ohm Line Chart, Gauge, Value
Inductance INDUCTANCE induct Henry HENRY h Line Chart, Gauge, Value
Ink Levels.Black INK_BLACK ink_blk % (0 to 100) PERCENT p Ink Levels (coming soon), Gauge, Line Chart, Value
Ink Levels.Cyan INK_CYAN ink_cya % (0 to 100) PERCENT p Ink Levels (coming soon), Gauge, Line Chart, Value
Ink Levels.Magenta INK_MEGENTA ink_mag % (0 to 100) PERCENT p Ink Levels (coming soon), Gauge, Line Chart, Value
Ink Levels.Yellow INK_YELLOW ink_yel % (0 to 100) PERCENT p Ink Levels (coming soon), Gauge, Line Chart, Value
Intrusion INTRUSION intrusion Digital (0/1) DIGITAL d Intrusion (coming soon), 2 State, Line Chart
Ionizing Radiation IONIZING_RADIATION ion_rad \* Electron Volts ELECTRON_VOLT ev Line Chart, Gauge, Value
Ergs ERGS erg
Joules JOULE j
Length LENGTH len \* Meter METER m Line Chart, Gauge, Value
Digital (0/1) DIGITAL d
Low/High LOW_HIGH null
Lighting LIGHTING_SENSE lighting_sense % (0 to 100) PERCENT p Lighting (coming soon), Gauge, Line Chart, Value
\* Lux LUX lux
Volts VOLTS v
Ratio RATIO r
Linear Acceleration.x axis LINEAR_ACCEL_X lin_acc_x Meters per second squared METER_PER_SEC_SQ mps2 Linear Acceleration (coming soon), Line Chart, Gauge, Value
Linear Acceleration.y axis LINEAR_ACCEL_Y lin_acc_y Meters per second squared METER_PER_SEC_SQ mps2 Linear Acceleration (coming soon), Line Chart, Gauge, Value
Linear Acceleration.z axis LINEAR_ACCEL_Z lin_acc_z Meters per second squared METER_PER_SEC_SQ mps2 Linear Acceleration (coming soon), Line Chart, Gauge, Value
Liquid LIQUID liquid \* Liter LITER l Line Chart, Gauge, Value
Gallon GALLON gal
Ounce OUNCE oz
Cubic centimeter CUBIC_CENT cc
Location.Latitude LOCATION_LAT loc_lat Latitude LATITUDE lat Map
Location.Longitude LOCATION_LONG loc_lon Longitude LONGITUDE long Map
Luminosity LUMINOSITY lum \* Lux LUX lux Gauge, Line Chart, Value
Volts VOLTS v
% (0 to 100) PERCENT p
Ratio RATIO r
Magnetic field strength H MAGNETIC_STRENGTH mag_str Amperes per meter AMP_METER ampm Magnetic Field H & B (coming soon), Magnetometer (coming soon), Line Chart, Gauge, Value
Magnetic field.x axis MAGNETIC_AXIS_X mag_x Tesla TESLA tesla Magnetometer (coming soon), Line Chart, Gauge, Value
Magnetic field.y axis MAGNETIC_AXIS_Y mag_y Tesla TESLA tesla Magnetometer (coming soon), Line Chart, Gauge, Value
Magnetic field.z axis MAGNETIC_AXIS_Z mag_z Tesla TESLA tesla Magnetometer (coming soon), Line Chart, Gauge, Value
Magnetic flux density B MAGNETIC_FLUX_DENSITY mag_flux Newton-meters per ampere NEWTON_METERS_AMP nma Magnetic Field H & B (coming soon), Magnetometer (coming soon), Line Chart, Gauge, Value
Mass MASS mass Kilogram KILOGRAM kg Line Chart, Gauge, Value
Memory MEMORY mem Kilobytes KB_BYTE kb Line Chart, Gauge, Value
\* Megabytes MB_BYTE mb
% (0 to 100) PERCENT p
Motion MOTION motion Digital (0/1) DIGITAL d Motion (coming soon), 2 State, Line Chart
Oil OIL oil Oil Barrel BARREL bbl Line Chart, Gauge, Value
\* gallon GALLON gal
liter LITER l
Orientation.Azimuth ORIENT_AZIMUTH ori_azim Degree Angle DEGREE deg Orientation (coming soon), Meter (coming soon), Line Chart, Gauge, Value
Orientation.Pitch ORIENT_PITCH ori_pitch Degree Angle DEGREE deg Orientation (coming soon), Meter (coming soon), Line Chart, Gauge, Value
Orientation.Roll ORIENT_ROLL ori_roll Degree Angle DEGREE deg Orientation (coming soon), Meter (coming soon), Line Chart, Gauge, Value
pH-Acidity ACIDITY acid Acidity ACIDITY acid Line Chart, Gauge, Value
Power POWER pow Watts WATT w Line Chart, Gauge, Value
Pollution.Nitrogen POLLUTION_NO2 no2 Nitrogen dioxide NO2 no2 Line Chart,Gauge,Value
Pollution.Ozone POLLUTION_O3 o3 Ozone O3 o3 Line Chart,Gauge,Value
Pressure PRESSURE press \* Pascal PASCAL pa Line Chart, Gauge, Value
Hecto Pascal HECTOPASCAL hpa
Bar BAR bar
Technical atmosphere TECH_ATMO at
Standard atmosphere STD_ATMO atm
Torr TORR torr
Pounds per square inch PSI psi
Proximity PROXIMITY prox \* Centimeter CENTIMETER cm Proximity (coming soon), Value, Gauge, Line Chart
Meter METER m
Digital (0/1) DIGITAL d
Radioactivity RADIOACTIVITY rad Becquerel BECQUEREL bq Line Chart, Gauge, Value
\* Curie CURIE ci
Radiation Exposure EXPOSURE_RADIATION expo_rad \* Roentgen ROENTGEN roent Line Chart, Gauge, Value
Coulomb/Kilogram COULOMB_PER_KG ckg
Rain Level RAIN_LEVEL rain_level Centimeter CENTIMETER cm Line Chart, Gauge, Value
\* Millimeter MILLIMETER mm
Relative Humidity RELATIVE_HUMIDITY rel_hum \* % (0 to 100) PERCENT p Gauge, Line Chart, Value
Ratio RATIO r
Resistance RESISTANCE res Ohm OHM ohm Line Chart, Gauge, Value
Rotation ROTATION rot Revolutions per minute RPM rpm Line Chart, Gauge, Value
\* Revolutions per second RPMS rpms
Radians per second rad/s radianps
Rotation Vector.scalar ROTATION_SCALAR rot_scal Cos(0/2) ROT_SCAL null Rotation Vector (coming soon), Line Chart, Gauge, Value
Rotation Vector.x axis ROTATION_X rot_x X \* sin (0/2) ROT_X null Rotation Vector (coming soon), Line Chart, Gauge, Value
Rotation Vector.y axis ROTATION_Y rot_y Y \* sin (0/2) ROT_Y null Rotation Vector (coming soon), Line Chart, Gauge, Value
Rotation Vector.z axis ROTATION_Z rot_z Z \* sin (0/2) ROT_Z null Rotation Vector (coming soon), Line Chart, Gauge, Value
Seismometer SEISMOMETER seis Microns (micrometers) /second, MICROS_PER_SEC micps Line Chart, Gauge, Value
\* Volts VOLTS v
Spectral Amplitude cm/hertz cmhz
Signal Noise Ratio SNR snr Decibels DB db Line Chart, Gauge, Value
Signal Strength SIGNAL_STRENGTH sig_str Decibels per milliwatt DBM dbm Line Chart, Gauge, Value
Smoke SMOKE smoke % (0 to 100) PERCENT p Smoke Detector (coming soon), Line Chart, Gauge, Value
Photodiode PHOTODIODE pz
\* Kiloelectron Volts KILOELEC_VOLT kev
Soil Moisture SOIL_MOISTURE soil_moist % (0 to 100) PERCENT p Line Chart, Gauge, Value
Soil pH SOIL_PH soil_ph Analog ANALOG null Line Chart, Gauge, Value
Soil Water Tension SOIL_WATER_TENSION soil_w_ten \* Kilopascal KILOPASCAL kpa Line Chart, Gauge, Value
Pascal PASCAL pa
Solid Volume SOLID_VOLUME solid_vol Cubic meter CUBIC_METER m3 Line Chart, Gauge, Value
Sound SOUND sound Decibels per milliwatt DBM dbm Line Chart, Gauge, Value
Specific Humidity SPECIFIC_HUMIDITY spec_hum Grams/Kilograms G_PER_KG gkg Line Chart, Gauge, Value
Speed SPEED speed Kilometer per hour KM_PER_H kmh Line Chart, Gauge, Value
\* Miles per hour MPH mph
Steps STEPS steps Steps STEPS null Line Chart, Gauge, Value
Storage STORAGE storage Bytes BYTE byte Line Chart, Gauge, Value
Kilobytes KB_BYTE kb
\* Megabytes MB_BYTE mb
Gigabytes GB_BYTE gb
Terabytes TB_BYTE tb
Stress STRESS stress Pascal PASCAL pa Line Chart, Gauge, Value
\* Hecto Pascal HECTOPASCAL hpa
Pounds per square inch PSI psi
Tank Level TANK_LEVEL tl Analog ANALOG null Line Chart, Gauge, Value
Temperature TEMPERATURE temp Fahrenheit FAHRENHEIT f Value, Line Chart, Gauge
\* Celsius CELSIUS c
Kelvin KELVIN k
Time TIME time \* Second s sec Time (coming soon), LCD (coming soon), Value
Milliseconds ms msec
minute mb min
hour h hour
day d day
month m month
year y year
Torque TORQUE torq \* Newton-meter nm newtm Line Chart, Gauge, Value
Joule j j
Turbidity TURBIDITY turb Nephelometric Turbidity Unit ntu ntu Line Chart, Gauge, Value
\* Formazin Turbidity Unit ftu ftu
Ultrasonic ULTRASONIC ultra Kilohertz khz khz Line Chart, Gauge, Value
Velocity VELOCITY velo Meters per second squared METER_PER_SEC mps Line Chart, Gauge, Value
Viscosity VISCOSITY visco Millipascal-second MILLIPASCAL_SEC mpas Line Chart, Gauge, Value
Voltage VOLTAGE voltage \* Volts VOLTS v Gauge, Line Chart, Value
Millivolts MILLIVOLTS mv
Volume VOLUME vol Cubic meter CUBIC_METER m3 Line Chart, Gauge, Value
Water WATER h20 \* Gallons per minute GPM gpm Line Chart, Gauge, Value
Cubic feet per second CUBIC_FEET_SEC cfs
Wavelength WAVELENGTH wave Meters METER m Line Chart, Gauge, Value
Weight WEIGHT weight \* Pounds POUND lbs Line Chart, Gauge, Value
Kilogram KILOGRAM kg
Received signal strength indicator RSSI rssi RSSI DBM dbm Line Chart
Wind Speed WIND_SPEED wind_speed Kilometer per hour KM_PER_H kmh Line Chart, Gauge, Value

* Denotes default value for Unit.

MQTT Messaging Topics

Using MQTT with Cayenne

MQTT is the preferred API protocol to send and receive data to and from myDevices dashboard. Payloads are plain text based or JSON, and topics follow a tree composed of a Username, a Client ID and a Channel ID, allowing for fine filtration and control. Therefore, MQTT does not require the use of a provisioning API. Data that is published to a backend topic can also be subscribed to by a user’s third party application.

Send Sensor data as JSON

Sensor payload

| Topic | PUB | SUB | |-------|-------------------------------------------|---|---| | v1/username/things/clientID/data/json | X | X |

A JSON string payload for

[
  {
     "channel": 1,
     "value": 16.4,
     "type": "temp",
     "unit": "c"
  },
  {
     "channel": 2,
     "value": 75,
     "type": "rel_hum",
     "unit": "p"
  },
  {
     "channel": 5,
     "value": 75,
     "type": "batt",
     "unit": "v"
  }
]

Send individual Sensor data

In order to send data, the channel ID needs to be appended to the data topic.

| Topic | PUB | SUB | |-------|-------------------------------------------|---|---| | v1/username/things/clientID/data/channel | X | X |

The data type and/or unit can be added to prefix the value, allowing the backend to process and display data without the need of configuring the data channel from the dashboard:

  • (string) type,unit=value

Receive Actuator command

In order to receive a command for a given data channel, the device must subscribe to the “cmd” topic.

| Topic | PUB | SUB | |-------|-------------------------------------------|---|---| | v1/username/things/clientID/cmd/channel |   | X |

Payload will contain a command sequence number followed by the value. The Developer is responsible for managing the value format.

  • (string) seq,value

Send Actuator Updated Value

In order to let the dashboard know of the current status of an actuator, the device must publish that value to the corresponding channel. This will ensure that the widget state (on/off) remains consistent with the state of the actuator.

| Topic | PUB | SUB | |-------|-------------------------------------------|---|---| | v1/username/things/clientID/data/channel | X |   |

Payload must contain simply the true binary value of a digital actuator (1/0) or numerical value for analog actuators.

  • (string) 1
  • (string) 0.8

Send command response

In order to let the system know of an actuator command, the device must publish a response on a common response topic.

| Topic | PUB | SUB | |-------|-------------------------------------------|---|---| | v1/username/things/clientID/response | X |   |

Payload must contain the status “ok” or “error”, as well as the command sequence number and an optional message that will be displayed to the user in case of error.

  • (string) ok,seq
  • (string) error,seq=message

Examples

Send Sensor Data to Channel 2

⇒ PUB v1/A1234B5678C/things/0123-4567-89AB-CDEF/data/2

temp,c=20.7

Receive Actuator Command on Channel 3

⇒ SUB v1/A1234B5678C/things/0123-4567-89AB-CDEF/cmd/3

⇐ 2otoExGxnMJz0Jn,0

Send updated Actuator value on Channel 3

⇒ PUB v1/A1234B5678C/things/0123-4567-89AB-CDEF/digital/3

1

Send a Command Response - OK

⇒ PUB v1/A1234B5678C/things/0123-4567-89AB-CDEF/response

ok,2otoExGxnMJz0Jn

Send a Command Response - Error

⇒ PUB v1/A1234B5678C/things/0123-4567-89AB-CDEF/response

error,2otoExGxn=ERROR MESSAGE

FAQs

Coming Soon!