This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

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 are collected once 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.

 Full Code

  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:

    sudo pip install mqtt-paho
    sudo pip install psutil

    Or for Python 3:

    sudo pip3 install mqtt-paho
    sudo pip3 install psutil

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

    from __future__ import print_function
    import paho.mqtt.publish as publish
    import psutil
    import string
    import random
  3. Define the variables for communicating with ThingSpeak. Edit the channel ID, write API key, and MQTT API Key.

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

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

    tTransport = "websockets"
    tPort = 80

  5. Create the topic string of 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

  6. Run a loop that calculates the system RAM and CPU performance every 20 seconds and publishes these values. Publish to fields 1 and 2 of the specified channel simultaneously using websockets.

    # Create a random clientID.
        for x in range(1,16):
        # 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