Use mqtt robust, use config file

This commit is contained in:
Jimmy 2021-05-29 14:59:03 +12:00
parent 9ee2603137
commit 71247d0154
1 changed files with 20 additions and 9 deletions

View File

@ -2,26 +2,37 @@ from machine import Pin
from time import sleep
import machine
import dht
from umqtt.simple import MQTTClient
from umqtt.robust import MQTTClient
import json
import gc
with open("config.json", 'r') as f:
config = json.load(f)
print(config)
led = Pin(2, Pin.OUT)
d = dht.DHT11(Pin(16))
d = dht.DHT11(Pin(12))
adc = machine.ADC(0)
server="10.1.1.162"
c = MQTTClient("umqtt_client", server)
c = MQTTClient("umqtt_client", config["mqtt"]["server"],ssl=True, user=config["mqtt"]["user"], password=config["mqtt"]["password"])
gc.enable()
while True:
led(0)
d.measure()
data = {'temp': d.temperature(), 'humid': d.humidity(),'light': adc.read(), 'id': 1}
data = {'temp': d.temperature(), 'humid': d.humidity(),'light': adc.read(), 'id': config["id"]}
print(data)
led(1)
try:
c.connect()
c.publish(b"sensors", json.dumps(data))
finally:
c.disconnect()
gc.collect()
sleep(2)