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

Error publishing sensor data to Thingspeak using MQTT on Raspberry Pi

我已将土壤湿度传感器模块和 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")

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

问题是因为 tPorttTransport 仅在 useUnsecuredWebsocketsTrue

时才定义

由于 useUnsecuredWebsockets 设置为 False 之前的几行,这将永远不会发生。

您可以将 useUnsecuredWebsockets 更改为 True 或在 if 语句中添加 else 子句以设置默认值。

if useUnsecuredWebsockets:
 tTransport= "websockets"
 tPort= 80
else:
 tTransport = "tcp"
 tPort= 1883