Search code examples
pythonmqttgrovepi+

(Python)How to use MQTT protocol to subscribe topics on Thingspeak.com and display it?


I have to write a python program using MQTT protocol to subscribe topics on thingspeak.com and display it on the screen of a Raspberry Pi. I found official help/documentation about publishing messages and field feeds to thingspeak.com, but they don't provide any information about how to subscribe a topic, e.g. what is the form of a topic string, what are the inclusions of that topic string etc. Does anyone have any clue about that?


Solution

  • According to the Thingspeak documentation: "ThingSpeak supports only publishing to channels using MQTT." (https://www.mathworks.com/help/thingspeak/mqtt-api.html) So at present I do not believe that there is a way to subscribe to a channel. This seems to make their MQTT implementation a bit pointless, but if you absolutely need to use it for publishing data it should still work.

    If necessary you could implement an ThingSpeak to MQTT bridge with the Python API (https://pypi.python.org/pypi/thingspeak/0.4.1). I use that API to bridge several sensors to my larger MQTT network and it works well.

    Here is an illustration of what I mean:

    import paho.mqtt.client as mqtt
    import time
    import thingspeak
    from ast import literal_eval
    
    MQTT_BROKER =
    MQTT_PORT =
    MQTT_TOPIC =
    THINGSPEAK_CHANNEL =
    THINGSPEAK_API = 
    UPDATE_INTERVAL = 
    
    client = mqtt.Client()
    client.connect(MQTT_BROKER, MQTT_PORT)
    client.loop_start()
    
    while True:
        thing = thingspeak.Channel(THINGSPEAK_CHANNEL, THINGSPEAK_API)
        n = literal_eval(thing.get_field_last(field='1'))
        client.publish(MQTT_TOPIC, n)
        time.sleep(UPDATE_INTERVAL)
    

    Note that the code is meant purely for illustration and was written off the top of my head with no revision. It has not been tested. But hopefully it will put you on the right path.