在Raspberry Pi上使用MQTT将传感器数据发布到Thingspeak时出错

时间:2018-01-16 23:03:05

标签: python raspberry-pi mqtt paho

我已将土壤湿度传感器模块和LDR连接到ADS1115 ADC(后者又连接到我的R Pi)。 我使用的是Python 2.7。 ADC工作正常,它分别从通道0和通道1打印土壤湿度模块和LDR的值。 我有以下代码使用以下指南将数据从土壤湿度模块发送到Thingspeak: https://www.mathworks.com/help/thingspeak/use-raspberry-pi-board-that-runs-python-websockets-to-publish-to-a-channel.html

https://github.com/adafruit/Adafruit_Python_ADS1x15

import time
import sys
from time import sleep
import paho.mqtt.publish as publish
import Adafruit_ADS1x15

#GPIO.setmode(GPIO.BOARD)

#Start of user config

channelID= "377509"
apiKey= "<APIKEY>"


#MQTT Connection Methods

useUnsecuredTCP= True

useUnsecuredWebsockets= False

useSSLWebsockets= False

mqttHost= "mqtt.thingspeak.com"

# You can use any Username.
mqttUsername = "SoilHumidityRpiDemo"

# Your MQTT API Key from Account > My Profile.
mqttAPIKey ="<APIKEY>"

if useUnsecuredWebsockets:
 tTransport= "websockets"
 tPort= 80

#Create topic string
topic= "channels/" + channelID + "/publish/" + apiKey


# Create an ADS1115 ADC (16-bit) instance.
adc = Adafruit_ADS1x15.ADS1115()

GAIN = 1

print('Reading ADS1x15 values, press Ctrl-C to quit...')

while True:
    m = adc.read_adc(0, gain=GAIN)
    print('Moisture Level:{0:>6}'.format(m))
    time.sleep(1)
    tPayload= "field1=%s" % m
    try:
      publish.single(topic, payload=tPayload, hostname=mqttHost, port=tPort, transport= tTransport,auth={'username':mqttUsername,'password':mqttAPIKey})
    except KeyboardInterrupt:
        break
    except:
        print ("There was an error publishing the data")

当我执行它时,出现错误消息“发布数据时出错”。 然而,当我只运行一个脚本来打印终端上ADC的土壤湿度值(没有代码通过MQTT将数据发送到Thingspeak)时,该脚本运行良好。

1 个答案:

答案 0 :(得分:1)

问题是因为/** * Execute the job. * * @return void */ public function handle() { $file = Storage::get($this->asset); $path = Storage::disk('s3')->put('contract-assets', $file, 'public'); dd($path); $this->project->addContractAsset($path); } tPort仅在tTransportuseUnsecuredWebsockets时定义

由于True设置为useUnsecuredWebsockets之前的几行,所以永远不会发生这种情况。

您可以将False更改为useUnsecuredWebsockets,也可以在if语句中添加else子句来设置默认值。

True