使用MQTT将多个值发布到thingspeak

时间:2018-03-08 17:44:53

标签: python json mqtt

我正在尝试使用mqtt发布多个随机数据,以便将数据从raspberry pi发送到thingspeaks。我想将10个temp值发布到thingspeaks字段,但它每15秒限制一个值。所以无论如何都要每隔15秒发送一个值列表,以便在事物峰值通道中按时间绘制图表?

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)

1 个答案:

答案 0 :(得分:0)

ThingSpeak支持批量更新,但您需要使用HTTP API而不是MQTT。

以下是如何从Raspberry Pi收集数据并一次发送多个值。

#! /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()