2424import xbee
2525
2626from digi import cloud
27- from machine import Pin
27+ from machine import I2C , Pin
2828from xbee import relay
2929
30+ from hdc1080 import HDC1080
31+
3032# Constants.
3133ITEM_OP = "operation"
3234ITEM_STATUS = "status"
4749
4850DEFAULT_TANK_LEVEL = 50.0 # 50 %
4951DEFAULT_VALVE_POSITION = False # Closed
52+ DEFAULT_TEMPERATURE = 21.0 # 21 C
5053DEFAULT_REPORT_INTERVAL = 60 # 1 minute
5154
5255TANK_DRAIN_RATE = 0.005 # 0.005 % / second
7578
7679DATAPOINT_LEVEL = "level"
7780DATAPOINT_VALVE = "valve"
81+ DATAPOINT_TEMPERATURE = "temperature"
7882
7983DRM_REQ_ON = "VALVE_ON"
8084DRM_REQ_OFF = "VALVE_OFF"
113117led_pin = Pin (LED_PIN_ID , Pin .OUT , value = VALUE_DISABLED )
114118btn_pin = Pin (BTN_PIN_ID , Pin .IN , Pin .PULL_UP )
115119
120+ sensor = None
121+
116122
117123def read_properties ():
118124 """
@@ -403,6 +409,23 @@ def reset_water_flow_vars():
403409 valve_open_time = time .time ()
404410
405411
412+ def get_tank_temperature ():
413+ """
414+ Reads the tank temperature from the I2C sensor and returns it.
415+
416+ Returns:
417+ The tank temperature.
418+ """
419+ if sensor is None :
420+ return DEFAULT_TEMPERATURE
421+
422+ try :
423+ # Read the temperature from the I2C sensor.
424+ return sensor .read_temperature (True )
425+ except OSError :
426+ return DEFAULT_TEMPERATURE
427+
428+
406429def process_drm_request (request ):
407430 """
408431 Processes the given DRM request.
@@ -455,16 +478,19 @@ def upload_sensor_data():
455478 # Calculate the new tank level.
456479 calculate_tank_level ()
457480 tank_level_f = "{:.2f}" .format (tank_level )
481+ tank_temperature_f = "{:.2f}" .format (get_tank_temperature ())
458482
459483 # print debug traces.
460484 print ("- Sending sensor values to DRM:" )
461485 print (" - Tank level: {} %" .format (tank_level_f ))
462486 print (" - Tank valve: {}" .format ("Open" if tank_valve_open else "Closed" ))
487+ print (" - Tank temperature: {} C" .format (tank_temperature_f ))
463488
464489 # Upload the samples to DRM.
465490 data = cloud .DataPoints ()
466- data .add (DATAPOINT_LEVEL , tank_level_f )
491+ data .add (DATAPOINT_LEVEL , tank_level_f , units = "%" )
467492 data .add (DATAPOINT_VALVE , int (tank_valve_open ))
493+ data .add (DATAPOINT_TEMPERATURE , tank_temperature_f , units = "C" )
468494 try :
469495 data .send (timeout = 60 )
470496 except OSError as e :
@@ -500,6 +526,7 @@ def main():
500526 Main execution of the application.
501527 """
502528 # Initialize variables.
529+ global sensor
503530 global identified
504531 global finished
505532
@@ -511,6 +538,12 @@ def main():
511538 print (" | End-to-End IoT Tank Monitoring Sample |" )
512539 print (" +---------------------------------------+\n " )
513540
541+ # Instantiate the HDC1080 peripheral.
542+ try :
543+ sensor = HDC1080 (I2C (1 ))
544+ except AssertionError :
545+ pass
546+
514547 # Configure the Bluetooth advertisement.
515548 config_advertisement ()
516549
0 commit comments