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 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.

Setup

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

2) Create an MQTT device by clicking Devices > MQTT at the top of the ThingSpeak page, then Add Device. When setting up the device and adding the new channel to its authorized list, click Download Credentials > Plain Text. For details, see Create a ThingSpeak MQTT Device. Use the saved credentials in the Code section below.

3) 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

Code

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

import paho.mqtt.publish as publish
import psutil
import string

2) Define the variables for communicating with ThingSpeak. Edit the channel ID and MQTT device credentials.

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

# The hostname of the ThingSpeak MQTT broker.
mqtt_host = "mqtt3.thingspeak.com"

# Your MQTT credentials for the device
mqtt_client_ID = "<YOUR-CLIENT-ID>"
mqtt_username  = "<YOUR-USERNAME>"
mqtt_password  = "<YOUR-MQTT-PASSWORD>"

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

t_transport = "websockets"
t_port = 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/" + channel_ID + "/publish"

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.

while (True):

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

    # build the payload string.
    payload = "field1=" + str(cpu_percent) + "&field2=" + str(ram_percent)

    # attempt to publish this data to the topic.
    try:
        print ("Writing Payload = ", payload," to host: ", mqtt_host, " clientID= ", mqtt_client_ID, " User ", mqtt_username, " PWD ", mqtt_password)
        publish.single(topic, payload, hostname=mqtt_host, transport=t_transport, port=t_port, client_id=mqtt_client_ID, auth={'username':mqtt_username,'password':mqtt_password})
    except (keyboardInterrupt)
        break
    except Exception as e:
        print (e) 

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

See Also

|

Related Examples

More About