使用MQTT将多个值发布到thingspeak

2024-10-04 11:21:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用mqtt发布多个随机数据,以将数据从raspberry pi发送到ThingSpeakes。我想把temp的10个值发布到thingspeaks字段,但是它限制了我每15秒一个值。那么,有没有必要每隔15秒发送一个值列表,在thingspeaks频道中用图表表示时间??在

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)

Tags: theto数据datatopicrandomcurrentpublish
1条回答
网友
1楼 · 发布于 2024-10-04 11:21:54

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()

相关问题 更多 >