从连接到Sonoff Tasmota的SENSOR DHT22的有效载荷中提取值

时间:2018-07-07 03:12:25

标签: python json mqtt mosquitto

我正在使用随Tasmora固件更新的Sonoff basic。我连接了温度传感器DHT22。在此设备上设置MQTT,以将传感器值发送到Linux PC上安装的Mosquitto。

我获取的数据格式为:

 mosquitto_sub -h my.dns.xxx -p 81111 -v -u user -P pass -t channels/sonoff/SENSOR/#

channels/sonoff/SENSOR {"Time":"2018-07-07T03:55:13","AM2301":{"Temperature":25.0,"Humidity":62.4},"TempUnit":"C"}
channels/sonoff/SENSOR {"Time":"2018-07-07T03:55:23","AM2301":{"Temperature":25.0,"Humidity":62.4},"TempUnit":"C"}
channels/sonoff/SENSOR {"Time":"2018-07-07T03:55:33","AM2301":{"Temperature":25.0,"Humidity":62.5},"TempUnit":"C"}
channels/sonoff/SENSOR {"Time":"2018-07-07T03:55:43","AM2301":{"Temperature":25.0,"Humidity":62.5},"TempUnit":"C"}
channels/sonoff/SENSOR {"Time":"2018-07-07T03:55:53","AM2301":{"Temperature":25.0,"Humidity":62.6},"TempUnit":"C"}

我需要将发布温度和湿度值的Python代码,这些代码将发布在Thingspeak.com上。

我已经有一些要发布的Python代码,但是它是用于OrangePI板的,以不同的方式读取值:

import dht22
import time
import datetime
import os



PIN2 = port.PA6
gpio.init()
n=75 #after every 150 (~10 minutes) load (connect to thingspeak) again!
i=0

channelId = "xxxxxx"         # Put your channel ID here,i.e.. the number from the URL, https://thingspeak.com/channels/285697
apiKey = "xxxxxxxxx"  # Put the API key here (the Write API Key from the API Keys tab in ThingSpeak)
client = mqtt.Client()
client.connect("mqtt.thingspeak.com",1883,60)


instance = dht22.DHT22(pin=PIN2)
os.system('clear')

while True:
    result = instance.read()
    if result.is_valid():
        i=i+1
        print 'I after increment is: ', i
        print 'VALID and i is:',i
        print("\033[37;1mLast valid input: \033[0m" + "\033[33;1m" + str(strftime("%d.%m.%Y %H:%M:%S", gmtime())) + "\033[0m")
        print("\033[37;1mTemperature: \033[1;31m%.2f C\033[0m" % result.temperature)
        print("\033[37;1mHumidity: \033[32;1m%.2f %%\033[0m\n" % result.humidity)
        if i == n-1:
            print 'I is: ', i
            print 'Now setting value i to zero\nLoading libary again'
            i=0
            print 'I after setting to zero is: ', i
            client = mqtt.Client()
            client.connect("mqtt.thingspeak.com",1883,60)
            client.publish("channels/%s/publish/%s" % (channelId,apiKey), "field1=" + str(result.temperature) + "&field2=" + str(result.humidity))
        else:
            client.publish("channels/%s/publish/%s" % (channelId,apiKey), "field1=" + str(result.temperature) + "&field2=" + str(result.humidity))
    else:
        print 'WE HAVE INVALID and i is:',i 
        time.sleep(4)

我非常确定它与我要搜索的内容非常相似,但是我无法编写代码。

有人可以帮我这几行代码吗?

2 个答案:

答案 0 :(得分:0)

听起来像您误解了MQTT是什么。 ThingsSpeak网站上有一个非常有用的参考,并且可能还有使用您的母语的更好的参考。

尤其要注意,MQTT始终需要一个经纪人和一个或多个客户端。客户可以订阅发布某个主题。代理将从客户端接收任何 publish 消息,并将其发送给所有已订阅的客户端。

在您的情况下,您具有作为MQTT 客户端的Sonoff基础(顺便说一句,它看上去与您所描述的完全不同吗?您的Linux PC充当经纪人,并且您还在PC上运行客户端(尽管my.dns.xxx暗示也涉及某种虚拟网络)。然后,您想连接到同时也是经纪人的ThingsSpeak。经纪人不与经纪人交谈,因此您要尝试做的事情行不通。

如果您想坚持自己拥有的东西(而不是简单地将Sonoff basic更改为ThingsSpeak的客户端,而不是PC),那么您需要的是 MQTT桥 >。桥接器允许您连接两个代理。桥实际上是订阅一个经纪人并将所有内容发布到另一个经纪人的客户端。

答案 1 :(得分:0)

好的,最后我了解了Python的基本知识。然后我编写了一个脚本。 看起来像:

import paho.mqtt.client as mqtt, time, sys
import paho.mqtt.client as mqtt

last_topic = ""
lasy_payload = ""

channelId = "xxxxxxx"         # Put your channel ID here,i.e.. the number from the URL, https://thingspeak.com/channels/285697
apiKey = "xxxxxxxxxxxxxxxx"  # Put the API key here (the Write API Key from the API Keys tab in ThingSpeak)
client = mqtt.Client()
client.connect("mqtt.thingspeak.com",1883,60)

# main
def on_connect(client, userdata, flags, rc):
    print("Connected...\n")
    client.is_connected = True

def on_message(client, userdata, message):
    ''' note: message is a tuple of (topic, payload, qos, retain)'''
    global last_topic, last_payload
    last_topic = message.topic
    last_payload = message.payload
    print("Message with topic: [" + last_topic + "] and payload [" + last_payload + "]")

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.is_connected = False
client.loop_start()
client.connect("localhost")

time.sleep(4)
if not client.is_connected:
    print("problem connecting to the MQTT server; please check your settings")
    sys.exit(1)

# ask for system status
time.sleep(1)
client.subscribe("channels/sonoff/SENSOR")
client.publish("cmnd/channels/sonoff/status",None)

# now wait for a time stamp from the sonoff; this could take an hour
client.subscribe("channels/sonoff/SENSOR")

while 1:
    if last_topic.startswith("channels/sonoff") and last_topic.endswith("SENSOR"):
        Payload_Temp = last_payload.find('"Temperature":')
        Payload_Hum = last_payload.find('"Humidity":')
        Temp = last_payload[Payload_Temp+14:Payload_Temp+14+4]
        Hum = last_payload[Payload_Hum+11:Payload_Hum+11+4]
        print("Temperature is: "+Temp +"C")
        print("Humidity is: "+Hum +"%")
        print("")
        client = mqtt.Client()
        client.connect("mqtt.thingspeak.com",1883,60)
        client.publish("channels/%s/publish/%s" % (channelId,apiKey), "field1=" + str(Temp) + "&field2=" + str(Hum))    
#        break
    time.sleep(32)# Couse Thingspeak accept only every 15 sec new value!

client.loop_stop()
client.disconnect()

它每隔32秒发送一次数据到Thingspeak! 工作正常!