3030mqtt_client = MQTT (** mqtt_settings , socket_pool = pool )
3131
3232# create a light_sensor object for analog readings
33- dht_in = board .A3 # change this accordingly
33+ dht_in = board .A0 # change this accordingly
3434dht_sensor = adafruit_dht .DHT11 (dht_in )
3535dht_sensor .measure () # update current data for Homie init
3636
3737# create the objects that describe our device
3838device = HomieDevice (mqtt_client , "my device name" , "lib-dht-sensor-test-id" )
3939dht_node = HomieNode ("DHT11" , "temperature/humidity sensor" )
4040dht_temperature_property = PropertyFloat (
41- "temperature" , init_value = dht_sensor .temperature , unit = "°F"
41+ "temperature" , init_value = dht_sensor .temperature * ( 9 / 5 ) + 32 , unit = "°F"
4242)
4343dht_humidity_property = PropertyPercent (
4444 "humidity" , datatype = "integer" , init_value = dht_sensor .humidity
@@ -60,7 +60,8 @@ def on_disconnected(client: MQTT, user_data, rc):
6060mqtt_client .on_connect = lambda * args : print ("Connected to the MQTT broker!" )
6161
6262# connect to the broker and publish/subscribe the device's topics
63- device .begin ()
63+ device .begin (keep_alive = 3000 )
64+ # keep_alive must be set to avoid the device's `$state` being considered "lost"
6465
6566# a forever loop
6667try :
@@ -73,9 +74,9 @@ def on_disconnected(client: MQTT, user_data, rc):
7374 mqtt_client .loop ()
7475 dht_sensor .measure () # update current data
7576 temp = device .set_property (
76- dht_temperature_property , dht_sensor .temperature
77+ dht_temperature_property , dht_sensor .temperature * ( 9 / 5 ) + 32
7778 )
78- print ("Temp:" , temp , dht_temperature_property .unit , end = " " )
79+ print ("Temp:" , temp , dht_temperature_property .unit [ - 1 ] , end = " " )
7980 humid = device .set_property (dht_humidity_property , dht_sensor .humidity )
8081 print ("Humidity:" , humid , dht_humidity_property .unit , end = "\r " )
8182 except MMQTTException :
0 commit comments