Main Content

Publish Using WebSockets in Python on a Raspberry Pi

This example shows how to use WebSockets on port 80 to publish to a ThingSpeak™ channel using a Raspberry Pi™ board that runs Python®. If you have more than one sensor value that you want to send to ThingSpeak, you can choose to publish multiple values to a channel feed. In this example, the CPU and RAM usage data of the Raspberry Pi board is collected every 20 seconds, and the values are published to a channel feed. Alternatively, if you have only one value to update, you can publish a single value to a channel field.


1) Create a new channel as shown in Collect Data in a New Channel.

2) Download the Paho MQTT client library for Python. You can use the command line to install the libraries. If you are using Python 2, use this code:

sudo pip install paho-mqtt
sudo pip install psutil

If you use Python 3, use this code:

sudo pip3 install paho-mqtt
sudo pip3 install psutil


1) Include the libraries print_function, paho.mqtt.publish as publish, psutil, string, and random, in your Python code.

from __future__ import print_function
import paho.mqtt.publish as publish
import psutil
import string
import random

2) Define the variables for communicating with ThingSpeak. Edit the channel ID, write API key, and MQTT API key.

string.alphanum = '1234567890avcdefghijklmnopqrstuvwxyzxABCDEFGHIJKLMNOPQRSTUVWXYZ'

# The ThingSpeak Channel ID.
# Replace <YOUR-CHANNEL-ID> with your channel ID.
channelID = "<YOUR-CHANNEL-ID>"

# The write API key for the channel.
# Replace <YOUR-CHANNEL-WRITEAPIKEY> with your write API key.

# The hostname of the ThingSpeak MQTT broker.
mqttHost = ""

# You can use any username.
mqttUsername = "TSMQTTRpiDemo"

# Your MQTT API key from Account > My Profile.

3) Define the connection type as websockets, and set the port to 80.

tTransport = "websockets"
tPort = 80

4) Create a topic string in the form shown in Publish to a Channel Feed that updates field 1 and field 2 of the specified channel simultaneously.

# Create the topic string.
topic = "channels/" + channelID + "/publish/" + writeAPIKey

5) Run a loop that calculates the system RAM and CPU performance every 20 seconds and publishes the calculated values. Publish to fields 1 and 2 of the specified channel simultaneously using WebSockets.


    clientID = ''

# Create a random clientID.
    for x in range(1,16):
        clientID += random.choice(string.alphanum)

    # get the system performance data over 20 seconds.
    cpuPercent = psutil.cpu_percent(interval=20)
    ramPercent = psutil.virtual_memory().percent

    # build the payload string.
    payload = "field1=" + str(cpuPercent) + "&field2=" + str(ramPercent)

    # attempt to publish this data to the topic.
        publish.single(topic, payload, hostname=mqttHost, transport=tTransport, port=tPort,auth={'username':mqttUsername,'password':mqttAPIKey})
        print (" Published CPU = ",cpuPercent," RAM = ", ramPercent," to host: " , mqttHost , " clientID= " , clientID)

    except (KeyboardInterrupt):

        print ("There was an error while publishing the data.")

Run the program and watch the channel for regular updates from your device.

See Also


Related Examples

More About