Menu

Rate this page:

Thanks for rating this page!

We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

Twilio Developer Kit for Broadband IoT: MQTT Quickstart

If you have the Twilio Broadband Developer Kit from SIGNAL or the Microsoft //build 2019 conference, this Quickstart will get you connected to an MQTT broker quickly.

In this Quickstart we'll:

  • Register your Twilio IoT SIM in the Programmable Wireless Console
  • Set up your Broadband IoT Developer Kit
  • Connect to a MQTT broker
  • Publish and subscribe to a MQTT topic
  • Build basic functionality on top of MQTT

The kit comes with a Twilio Programmable Wireless SIM suitable for Broadband IoT applications which need low latency, high bandwidth and secure connectivity.

What's in the Twilio Broadband IoT Developer Kit?

  • Twilio IoT SIM (after, also see our Quickstart using Azure)
  • Raspberry Pi 3b+
  • Seeed LTE Cat 1 cellular module (+ antennas)
  • I2C Temperature and Humidity sensor
  • I2C OLED display
  • Power adapter and switch
  • USB - mini USB cable
  • Ethernet cable and ethernet - USB adapter

What is MQTT?

MQTT is a publish/subscribe messaging protocol built on top of TCP/IP. It stands for Message Queuing Telemetry Transport.

Although the Raspberry Pi can handle other protocols, it's an excellent choice since it's so portable. The majority of lower-specced devices have MQTT capabilities; sticking with MQTT means your device ecosystem is expandible.

If you need it, download the latest Twilio Raspberry Pi image here (v1.1).

Let's get started

Sign up for - or sign in to - Twilio

If you haven't yet, you'll need to sign up for an account with Twilio. You can sign up for a free Twilio trial account here.

If you already have an account, you can login here.

Register your Twilio IoT SIM

Follow these steps to create a Rate Plan and Activate your SIM on the network.

Enter the SIM registration codetob-sim.png

  1. Open the Programmable Wireless Console.
  2. From the Programmable Wireless menu, click SIMs and click the red plus ('+') button to open the Register a Starter SIM page.
  3. Find the 10 alphanumeric character SIM registration key in the center of the reverse side of the Narrowband IoT SIM chip card:
  4. Enter this number in the Registration Code field.
  5. Click Register SIM Card.

register-tob-sim1.png

Choose a Unique SIM Name

  1. In the Unique Name field, give your SIM a friendly unique name. This is used to identify this SIM in the SIMs section of the Console.
  2. Click Continue.

Create a Rate Plan

  1. Click the red + button to create a Rate Plan.
  2. In the dialog that appears, give the Rate Plan a unique name. This will be used in the Console.
  3. Click Save to continue.

The Rate Plan is now set.

You can find more information on rate plans in Understanding Rate Plans.

Activate your SIM

  1. Click 'Activate' to activate your SIM on the network
  2. Wait for up to a couple minutes as your SIM activates

View SIM configuration details

  1. Once your new SIM has been activated, the View SIM Detail button should appear
  2. Click the View SIM Detail button to open the Configure tab for your newly activated SIM

sim-activation.png

My SIM is Active, what next?

Set up the hardware

Now, it's time to put all the hardware together. Work through these steps carefully, it's easy to break some of the fragile parts.

Insert the SIM Card and Attach the LTE Antenna

Insert the smallest form factor SIM into the SIM slot on the Pi Hat board.

sim-insert.png

The Broadband IoT Developer Kit comes with two antennas: LTE Main and LTE Div.

We will use the LTE Main antenna. Connect the black rectangular LTE PCB antenna to the receptacle labeled LTE Main on the back of the Pi Hat board (as shown in the photo).

Connect the Pi Hat to the Raspberry Pi

Use the USB to micro USB angled cable to connect the Pi Hat (the upper board) to the Raspberry Pi (the lower board). The larger side goes to the Pi while the smaller goes to the MicroUSB port onboard the Pi Hat.

cable-setup.png

Connect the Display and Temperature Sensor

The temperature sensor and display are individually addressable. It doesn't matter the order you connect the two as long as you make a good connection.

Remove either from the package, and connect the included Grove cable between it and one Grove header on the Pi Hat. Likewise, remove the other and connect it to the second Grove header.

display-sensor.png

Connect the power adapter to the Raspberry Pi

network-light.png

  1. Carefully plug the included Pi Power Adapter and switch to the wall
  2. Attach the other side of tha adapter to the power jack of the Raspberry Pi (If the Pi is still oriented like the above, it'll be in the lower left part of the Pi's PCB)
  3. You'll see LEDs come to life quickly - note the green LED on the left edge of the Raspberry Pi PCB (busy light) and the LEDs on the Pi Hat
  4. Since you registered the SIM you should soon (🤞) see the blue connectivity light on the Pi Hat as it connects to the cell network via Twilio
  5. Once the green light on the Pi stops (or slows down) blinking, you're ready to try to log in

SSH to the Raspberry Pi to test the components

We're getting close!

Assuming the Pi boots okay, you're ready to log in and test.

We've added some code that automatically puts the Pi at address 192.168.253.100. Windows users should use PuTTYor Powershell's built-in ssh client, while *NIX and Mac OSX users can use a built-in terminal to log into the Pi.

(If you are on a shared computer or you have used a previous version of the firmware you might see a certificate error. Follow the steps in the error message to remove the server key and try again.)

  1. When the green light on the Pi PCB stops blinking:

    ssh pi@192.168.253.100

    Note: If you have trouble reaching the host, try removing and re-inserting the USB ethernet adapter. Sometimes the dhcp client on your computer won't immediately re-query the Pi for an IP address.

  2. If you see the password prompt, enter the password build19
  3. First, test the temperature sensor with the following command:

    python /home/pi/grove.py/grove/grove_I2C_High_Accuracy_tem_hum_SHT35_sensor.py

    (Did you see a temperature and humidity value displayed to the Pi console? If not, use shutdown -h 0 to power down, double check all connections are tight, then start again with power-up)

    You'll see output to the console only for this command... for now!

  4. Use "control-c" to exit the temperature process
  5. Next, keep your eye on the display and run the command:

    grove_lcd_1.2inches

If you were successful, you should see "Hello, World!" on the attached display.

Wow, pretty cool! Let's talk to clouds.

Connect a web client to the MQTT Broker

For this quickstart, we're going to use the excellent open MQTT broker provided by HiveMQ. We'll also use their MQTT web client.

(You can find other public MQTT brokers here).

Note: HiveMQ's broker is completely open, and we'll be using it unencrypted. Anyone can subscribe or publish to your topic.

In production, use encrypted communications only. Additionally, either set up your own MQTT broker or get a private broker service.

Let's connect to the broker now.

  1. Visit HiveMQ's MQTT web client Page
  2. Hit the 'Connect' button:
    Connect to the HiveMQ Public Broker
  3. Subscribe to the topic SOMERANDOMSTRING/# (SOMERANDOM string is something you make up - just keep note of it for later):
    Subscribe to a MQTT Topic HiveMQ
  4. Under "Publish" use the topic SOMERANDOMSTRING/info and send the message "Hello, World!":
    "Hello, World!" Message MQTT
  5. Verify you got the message

If that worked, excellent! You're ready to wire up the Raspberry Pi.

Great, I love Raspberry Pi!

Connect to the MQTT Broker from the Pi

Go back to your terminal or PuTTY window where you SSHd into the Pi. We're going to walk through the steps to connect the Pi to the broker.

  1. On the Raspberry Pi, run the following command:
    wget https://s3.amazonaws.com/com.twilio.prod.twilio-docs/quest/programmable_wireless/broadband/telemetry.py -P /home/pi/grove.py/
  2. Open the file in a text editor on the Pi, such as "nano": nano /home/pi/grove.py/telemetry.py
  3. Edit all of the sections in the file under # EDIT THESE:
    - MQTT_ADDRESS: The MQTT server address to connect to, for example broker.hivemq.com
    - MQTT_CLIENT_ID: Set it to the same as SOMERANDOMSTRING, for example twilio-raspberry-pie-toppings
    - MQTT_PUBLISH_TOPIC: Same as the above, followed by the `/info` path e.g. twilio-raspberry-pie-toppings/info
    - MQTT_STATE_TOPIC: Same as the CLIENT_ID, followed by the `/state` path e.g. twilio-raspberry-pie-toppings/state
    - MQTT_BROKER_PORT: 1883 is the unencrypted MQTT port. If you have an encrypted broker, change this to the port they specify (usualy 8883)
    - MQTT_USERNAME: For many public brokers, this is ignored. If you are using a private, enter the username.
    - MQTT_PASSWORD:For many public brokers, this is ignored. If you are using a private broker, enter the password.

  4. Exit the text editor (for example in nano, "Control-X")
  5. Save the file (for example in nano, "y" then "Enter")

Telemetry Script Python

Run the Raspberry Pi MQTT Script

Ready to test some magic?

  1. Open the browser tab where you have the MQTT Web Client
  2. In the terminal or PuTTY window of the Raspberry pi, run these commands:
    cd /home/pi/grove.py
    python telemetry.py

  3. And watch the web client...

You should soon see humidity and temperature data from the Raspberry Pi show up as messages in the MQTT web client:

Receive Temperature/Humidity Messages MQTT

Excellent! Now let's look at how to send data back to the Pi.

Show Me How to Send MQTT Messages from the Cloud

Receiving published MQTT messages on the Raspberry Pi

The Python App you downloaded already can handle incoming messages via the Paho MQTT library running on the Pi.

Instead of walking you through the setup, let's look at the capabilities now, then how you can change the logic for your own needs.

Change the temperature units

In the HiveMQ web client, publish the message:

{"units": "fahrenheit"}

to the topic: SOMERANDOMSTRING/state

(for example, twilio-raspberry-pie-toppings/state)

... then wait up to 60 seconds. While the Pi will register the command quickly, it won't switch units until the next temperature refresh (60 seconds by default).

Switch to image mode

In the MQTT client, publish the message:

{"display": "image"}

to the topic: SOMERANDOMSTRING/state

(for example, twilio-raspberry-pie-toppings/state)

You should very quickly see the Twilio logo pop up on the small display. Nice!

Show any image on the internet

That's not all, though - the default Python application can show any image on the internet. Now send the message:

{"display": "image", "displayUrl": "https://dazedimg-dazedgroup.netdna-ssl.com/830/azure/dazed-prod/1150/0/1150228.jpg"}

To the same topic. (Note, you can change displayUrl to any publicly available GIF, JPEG, or PNG)

Don't give up, we won't let you down.

Switch back to temperature mode

If you are in image mode, you can also switch back. In the MQTT client, now publish the message:

{"display": "temperature"}

to the topic: SOMERANDOMSTRING/state

(for example, twilio-raspberry-pie-toppings/state)

And... up to 60 seconds later (depending on refresh) you're back to a temperature display.

Change the logic when receiving MQTT messages

All of the logic for interfacing with the temperature and humidity seensor, display, and MQTT is inside the Python app on the Raspberry Pi, /home/pi/grove.py/telemetry.py.

Modify the interface to the temperature sensor

For the temperature and humidity sensor, we're using Seeed's grove library. You can see where we set it up in:

class GroveTemperatureHumiditySensorSHT3x(object):

And when we call

sensor.read() in twilio_telemetry_loop(), we simply take the temperature and humidity at the time and put it in a JSON structure.

Change the logic to work with the display

We're using the Luma LCD library for Python to interface with the display. Wherever you see draw.text, we are sending strings to the display at a location.

For example, this function called when you load the script will show the splash screen:

with canvas(device) as draw:
    draw.rectangle(device.bounding_box, outline="white", fill="black")
    draw.text((5, 10), "Twilio Trust Onboard", fill="white")
    draw.text((42, 40), "presents", fill="white")
    draw.text((44, 65), "M Q T T", fill="white")
    draw.text((12, 80), "T E L E M E T R Y", fill="white")

Images are slightly more complicated since they may be larger than the screen. We're using the Pillow library to reduce dimensions to fit the display.

This code resizes an image (identified by URI) using Python and displays it on the SH1106 LCD:

def update_image_on_display(url):
    global CURRENT_LOGO
    if url != "":
        try:
            logo = Image.open(
                urllib2.urlopen(url)
            ).convert("RGBA")

            width, height = logo.size
            if width > 128 or height > 128:
                logo.thumbnail(device.size)

            if logo:
                CURRENT_LOGO = logo

        except:
            pass

    background = Image.new("RGBA", device.size, "white")
    posn = ((device.width - CURRENT_LOGO.width) // 2, 0)

    background.paste(CURRENT_LOGO, posn)
    device.display(background.convert(device.mode))

Modify the MQTT message callback functionality

The entry point for the app is where we set up a callback function (client.on_message = on_message) for MQTT messages on the state topic:

##############################################
# Called from the command line               #
##############################################
if __name__ == '__main__':
    time.sleep(5)
    print ("Starting the Twilio Broadband MQTT Demo...")

    client.on_message = on_message
    client.subscribe(MQTT_STATE_TOPIC)
    twilio_telemetry_loop()

And if you turn your attention to the on_message function, you can see how we're handling incoming messages. We try to extract certain keys and values from the JSON:

def on_message(client, userdata, message):
    global UNITS
    global DISPLAY_TYPE
    print("Message received ", str(message.payload.decode("utf-8")))
    print("Message topic=", message.topic)
    print("Message qos=", message.qos)
    print("Message retain flag=", message.retain)

    try:
        msg = json.loads(str(message.payload.decode("utf-8")))
        print(msg)

        if 'units' in msg and \
                msg['units'] in ('fahrenheit', 'celsius'):
            UNITS = msg['units']

        if 'display' in msg:
            if msg['display'] == "image":
                DISPLAY_TYPE = 'image'
                if 'displayUrl' in msg:
                    update_image_on_display(msg['displayUrl'])
                update_image_on_display("")
            if msg['display'] == "temperature":
                DISPLAY_TYPE = 'temperature'
    except:
        # Probably wasn't JSON
        pass

Great stuff, thanks! What's next?

You now have the roots of a temperature and humidity monitoring system. It's all ready for you to scale up or move over to a private MQTT broker.

You can publish and subscribe to MQTT topics on the Raspberry Pi. You can also change the behavior of the device from the cloud, and send fun images back to the board.

With that, you're ready to build your own more complex use case!

We hope you enjoyed this MQTT Quickstart with the Developer Kit for Broadband IoT. We can't wait to see what you build next.

Suggested Content

Rate this page:

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.