简体   繁体   中英

publish multiple values to thingspeak using MQTT

I am trying to publish a multiple random data using mqtt to send data from raspberry pi to thingspeaks. i want to publish the 10 values of temp to thingspeaks field but it limits me to one value every 15 seconds. so is there anyway to send a list of values every 15 second to graph it with time in thingspeaks channels??

temp = []
current = []
while(1):
   # get the system performance data over 20 seconds.
   for i in range(10):
       temp.append(random.randint(0, 100))
       current.append(random.randint(0, 100))
   # build the payload string.
     payload = "field1=" + str(temp) + "&field2=" + str(current)
     # attempt to publish this data to the topic.

     try:
         publish.single(topic, payload, hostname=mqttHost, transport=tTransport, port=tPort,auth={'username':mqttUsername,'password':mqttAPIKey})
         print (" Published temp =",temp," current =", current," to host: " , mqttHost , " clientID= " , clientID)

     except (KeyboardInterrupt):
         break

     except:
         print ("There was an error while publishing the data.")
     time.sleep(15)

ThingSpeak supports bulk update, but you need to use the HTTP API instead of MQTT.

Here is how to collect data from the Raspberry Pi and send multiple values at once.

#! /usr/bin/env python

'''

This example shows how to use the RaspberryPi running Python 2.7 to collect CPU temperature and CPU utilization as a percentage. The 
data is collected once every 15 seconds and the channel is updated once every 2 minutes. Since the RaspberryPi
does not have a real-time clock, relative time stamps are used. 

'''

# Import the necessary libraries

import urllib2 as ul
import json
import time
import os
import psutil

# Set the global variables to collect data once every 15 seconds and update the channel once every 2 minutes
lastConnectionTime = time.time() # Track the last connection time
lastUpdateTime = time.time() # Track the last update time
postingInterval = 120 # Post data once every 2 minutes
updateInterval = 15 # Update once every 15 seconds


writeAPIkey = "YOUR-CHANNEL-WRITEAPIKEY" # Replace YOUR-CHANNEL-WRITEAPIKEY with your channel write API key
channelID = "YOUR-CHANNELID" # Replace YOUR-CHANNELID with your channel ID
url = "https://api.thingspeak.com/channels/"+channelID+"/bulk_update.json" # ThingSpeak server settings
messageBuffer = []

def httpRequest():
    '''Function to send the POST request to 
    ThingSpeak channel for bulk update.'''

    global messageBuffer
    data = json.dumps({'write_api_key':writeAPIkey,'updates':messageBuffer}) # Format the json data buffer
    req = ul.Request(url = url)
    requestHeaders = {"User-Agent":"mw.doc.bulk-update (Raspberry Pi)","Content-Type":"application/json","Content-Length":str(len(data))}
    for key,val in requestHeaders.iteritems(): # Set the headers
        req.add_header(key,val)
    req.add_data(data) # Add the data to the request
    # Make the request to ThingSpeak
    try:
        response = ul.urlopen(req) # Make the request
        print response.getcode() # A 202 indicates that the server has accepted the request
    except ul.HTTPError as e:
        print e.code # Print the error code
    messageBuffer = [] # Reinitialize the message buffer
    global lastConnectionTime
    lastConnectionTime = time.time() # Update the connection time


def getData():
    '''Function that returns the CPU temperature and percentage of CPU utilization'''
    cmd = '/opt/vc/bin/vcgencmd measure_temp'
    process = os.popen(cmd).readline().strip()
    cpuTemp = process.split('=')[1].split("'")[0]
    cpuUsage = psutil.cpu_percent(interval=2)
    return cpuTemp,cpuUsage

def updatesJson():
    '''Function to update the message buffer
    every 15 seconds with data. And then call the httpRequest 
    function every 2 minutes. This examples uses the relative timestamp as it uses the "delta_t" parameter. 
    If your device has a real-time clock, you can also provide the absolute timestamp using the "created_at" parameter.
    '''

    global lastUpdateTime
    message = {}
    message['delta_t'] = time.time() - lastUpdateTime
    Temp,Usage = getData()
    message['field1'] = Temp
    message['field2'] = Usage
    global messageBuffer
    messageBuffer.append(message)
    # If posting interval time has crossed 2 minutes update the ThingSpeak channel with your data
    if time.time() - lastConnectionTime >= postingInterval:
        httpRequest()
    lastUpdateTime = time.time()

if __name__ == "__main__":  # To ensure that this is run directly and does not run when imported 
    while 1:
        # If update interval time has crossed 15 seconds update the message buffer with data
        if time.time() - lastUpdateTime >= updateInterval:
            updatesJson()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM