atm我正在使用python paho mqtt客户机和mysql来存储通过微控制器收集的天气数据(温度/湿度)。
设置:
raspian、mariadb和mosquitto经纪人的raspi
将数据发布到代理的esp8266
我编写了以下代码从代理获取数据并将其写入数据库:
主.py
import paho.mqtt.client as mqtt #import client1
from time import sleep
import json
from Datenbank import *
from datetime import *
i=0
def on_log(client,userdata,level,buf):
print("log: "+buf)
def on_connect(client,userdata,flags,rc):
if rc==0:
print("connected OK")
else:
print("Bad connection Returned code=",rc)
def on_disconnect(client,userdata,flags,rc=0):
print("Disconnected result code "+str(rc))
def on_message(client,userdata,msg): #callback function
topic=msg.topic
m_decode=str(msg.payload.decode("utf-8","ignore"))
print("message received",m_decode)
m_in=json.loads(m_decode)
dbG.writeData(m_in["Temperature"],m_in["Humidity"])
print("Data Written")
print(datetime.now())
db=db()
db.connectToDb("WeatherStation")
broker="192.168.0.10"
client=mqtt.Client("Sensor1_Client")
client.connect(broker)
print("Connecting to broker",broker)
client.on_connect=on_connect
client object
# client.on_disconnect=on_disconnect
client.on_log=on_log
client.on_message=on_message
client.subscribe("home/Sensor1")
client.loop_forever()
日期银行.py
import MySQLdb as db
from datetime import *
class db:
def __init__(self):
self.HOST = "192.168.0.10"
self.PORT = 3306
self.USER = "xxx"
self.PASSWORD = "xxx"
def connectToDb(self,DB):
try:
self.connection = db.Connection(host=self.HOST, port=self.PORT,
user=self.USER, passwd=self.PASSWORD, db=DB)
self.connection.autocommit(True)
print("Connection established")
except Exception as e:
print(e)
def writeData(self,temp,hum):
now=datetime.now()
Full_Date=now.strftime("%y.%m.%d")
current_year=now.strftime("%Y")
current_month=now.strftime("%m")
current_day=now.strftime("%d")
current_time=now.strftime("%H:%M")
dbhandler = self.connection.cursor()
dbhandler.execute("""INSERT INTO TempHum(Full_Date,Day,Month,Year, Time,Temperature,Humidity) VALUES(%s,%s,%s,%s,%s,%s,%s)""",(Full_Date,current_day,current_month,current_year,current_time,temp,hum))
我在raspi上加载了脚本,并通过键入以下内容打开main.py via屏幕:
“python main.py&”
这个构造工作得很好,但是在第15/16次之后,脚本和数据的插入停止了。
一开始我用一个简单的“client.loop\u start()”和“sleep(1000)”尝试了一下,但都没用。
有人知道为什么剧本不起作用吗?
问候语,
罗宾
暂无答案!
目前还没有任何答案,快来回答吧!