This commit is contained in:
xyj 2023-12-01 20:21:48 +08:00
parent 4397b75fa2
commit 83e70e8508
2 changed files with 58 additions and 35 deletions

View File

@ -34,7 +34,7 @@ class MQTT:
self.client.on_connect = self.on_connect
self.client.on_message = self.on_message
# Establish a connection
self.client.connect('192.168.1.27', 1883)
self.client.connect('60.204.152.17', 1883)
# Publish a message
self.client.loop_forever(retry_first_connection=True)

View File

@ -204,9 +204,9 @@ def run_with_client(client):
'wind_speed': speedwind_data,
'wind_direction': winddirection_data}
data = LOT_DATA(**data, create_time=int(time.time()))
t = LOT_DATA(**data, create_time=int(time.time()))
# TODO 判断数据是否正常
add(data)
add(t)
# 发送给服务器
client.publish('lot_data', payload=data, qos=0)
@ -378,39 +378,62 @@ def run_no_client():
add(data)
class UPLOAD:
def __init__(self):
self.client = mqtt.Client()
self.client.username_pw_set("ceshi", "123456")
# Specify callback function
self.client.on_connect = self.on_connect
# Establish a connection
self.client.connect('192.168.1.27', 1883)
# Publish a message
self.client.loop_forever()
self.time = 3
def on_connect(self, client, userdata, flags, rc):
if rc == 0:
print("连接成功,执行数据推送和本地存储")
self.t1()
else:
if self.time != 0:
self.time -= 1
client.reconnect()
else:
print("3次失败执行本地存储")
self.t2()
def t1():
import time
for i in range(100):
time.sleep(2)
data = {
"wind_speed": 1,
"wind_direction": 6,
"ambient_temperature": 66,
"ambient_humidity": 78,
"carbon_dioxide": 94,
"ambient_air_pressure": 48,
"rainfall": 3,
"ambient_lighting": 59,
"soil_temperature": 71,
"soil_moisture": 19,
"soil_conductivity": 62,
"soil_PH": 49,
"soil_potassium_phosphate_nitrogen": 5,
"soil_potassium_phosphate_phosphorus": 5,
"soil_potassium_phosphate_potassium": 86,
"create_time": int(time.time())
}
client.publish('lot_data', payload=json.dumps(data, ensure_ascii=False), qos=0)
# Message receiving callback
def t1(self):
for i in range(3):
self.client.publish('lot_data', payload='1', qos=0)
def t2(self):
def t2():
print("1")
if __name__ == '__main__':
up = UPLOAD()
time = 3
from threading import Thread
def on_connect(client, userdata, flags, rc):
global time
if rc == 0:
print("连接成功,执行数据推送和本地存储")
nt1 = Thread(target=t1)
nt1.start()
else:
if time != 0:
time -= 1
client.reconnect()
else:
print("3次失败执行本地存储")
nt2 = Thread(target=t2)
nt2.start()
client = mqtt.Client(transport="websockets")
client.username_pw_set("demo", "123456")
# Specify callback function
client.on_connect = on_connect
# Establish a connection
client.connect('ceshi-mqtt.lihaink.cn', 8083)
# Publish a message
client.loop_forever()
# Message receiving callback