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 of the Raspberry Pi board are collected once every 20 seconds, and the values are published to a channel feed. Alternatively, you can publish a single value to a channel field if you have only one value to update.
Create a new channel as shown in Collect Data in a New Channel.
Download the Paho MQTT client
library for Python. Include the libraries
import psutil, and
__future__ import print_function in your Python code.
import paho.mqtt.publish as publish import psutil from __future__ import print_function
Define the channel ID, write API key, and ThingSpeak MQTT broker.
# 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 apiKey = "<YOUR-CHANNEL-WRITEAPIKEY>" # The Hostname of the ThinSpeak MQTT broker mqttHost = "mqtt.thingspeak.com"
Define the connection type as
and set the port to
tTransport = "websockets" tPort = 80
Create the topic string of the form shown in Publish to a Channel Feed to update field 1 and field 2 of the specified channel simultaneously.
# Create the topic string topic = "channels/" + channelID + "/publish/" + apiKey
Run a loop that calculates the system RAM and CPU performance every 20 seconds and publishes these values to fields 1 and 2 of the specified channel simultaneously using websockets.
while(1): # get the system performance data cpuPercent = psutil.cpu_percent(interval=20) ramPercent = psutil.virtual_memory().percent print (" CPU =",cpuPercent," RAM =", ramPercent) # build the payload string payload = "field1=" + str(cpuPercent) + "&field2=" + str(ramPercent) # attempt to publish this data to the topic try: publish.single(topic, payload, hostname=mqttHost, transport=tTransport, port=tPort) except (KeyboardInterrupt): break except: print ("There was an error while publishing the data.")