Understanding the edge device code

The main.py file is run after boot.py whenever a MicroPython microcontroller is turned on. In our code, we have a continuous loop that checks the temperature every 60 seconds and compares it to the temperature threshold. If the temperature is too low, the heater is turned on and a cycle counter is incremented. Once the counter reaches the maximum number of cycles, the heater is turned off for 6 hours and a LoRa message is sent out indicating that the heater has been disabled.

The following is a diagram of the main.py file:

Our code reads the value from a temperature sensor using the DHT11 class. The LoRaMessage class is used to send LoRa messages to the gateway device, indicating whether the heater is enabled or disabled. The following is the code that disables the heater in main.py:

if(num_cycles >= max_cycles):
heater.off()
num_cycles = 0
timer = time() + 21600

while time() < timer():
message.send_message("heater_enabled: False")
print("heater_enabled: False")
sleep(2)

message.send_message("heater_enabled: True")
print("heater_enabled: True")

As we can see in the code, timer is set to be 6 hours in the future (21600). While time (determined by time()) is less than timer, we send out a LoRa message every 2 seconds indicating that the heater is currently not enabled (heater_enable: False). Once the 6 hours have passed, a LoRa message is sent indicating that the heater is now enabled (heater_enable: True).

By using classes in our code, we can abstract details and have main.py with a few lines of code, which makes it easier to read and debug. In the next section, we will set up an MQTT broker using the CloudMQTT service.