Facebook
From hellriser, 3 Years ago, written in Python.
Embed
Download Paste or View Raw
Hits: 209
  1. from time import sleep
  2. from umqtt.simple import MQTTClient
  3. from machine import Pin
  4. import machine
  5. from dht import DHT22
  6. import ujson
  7. import utime
  8. import ntptime
  9.  
  10.  
  11.  
  12. # +-------------------------------------+
  13. # |          MQTT Section               |
  14. # +-------------------------------------+
  15.  
  16. with open('client.key.der') as f:                       # reading client key
  17.         key_data = f.read()
  18. with open('client.cert.der') as f:                      # reading client cert
  19.         cert_data = f.read()
  20.  
  21. server = 'server.ml'                                    # MQTT Server Address
  22. client_id = 'ESP8266_DHT22_Sensor_Polcia'               # client id
  23. topic = b'temperature_humidity'
  24. location = 'Pokój Polci 2'                              # location of the sensor
  25. counter = 1                                             # Control number
  26. dsleep = 600                                            # number of seconds ESP is to sleep
  27. dbr = 3                                                 # delay between readings in getData function
  28. nom = 5                                                 # number of measurements before taking the median
  29. save2db = True                                          # Switch to save or not data to database
  30. debug = True                                            # if debug = True then write to debug.log
  31.  
  32. def deep_sleep(msecs):                                  # https://randomnerdtutorials.com/micropython-esp8266-deep-sleep-wake-up-sources/
  33.     if debug: write2debug('Inside deep_sleep')          # you need to connect GPIO16 (D0) to the RST pin so that the ESP8266 can wake itself up.
  34.     rtc = machine.RTC()                                 # configure RTC.ALARM0 to be able to wake the device
  35.     rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)
  36.    
  37.     rtc.alarm(rtc.ALARM0, msecs)                        # set RTC.ALARM0 to fire after X milliseconds (waking the device)
  38.  
  39.     # put the device to sleep
  40.     if debug: write2debug('Going to sleep...\n-------------------------------\n')
  41.     machine.deepsleep(msecs)
  42.  
  43. def median(lst):                                        # Calculate median from given list of values
  44.     sortedLst = sorted(lst)
  45.     lstLen = len(lst)
  46.     index = (lstLen - 1) // 2
  47.    
  48.     if (lstLen % 2):
  49.         return sortedLst[index]
  50.     else:
  51.         return (sortedLst[index] + sortedLst[index + 1])/2.0
  52.  
  53. def getCurrentDatetime():
  54.  
  55.     ntptime.settime()                                   # Synchronise the system time using NTP
  56.  
  57.     GMT = 1                                             # we are at GMT+1 zone, so one hour ahead
  58.    
  59.     sGMT = GMT * 3600                                   # hours to seconds
  60.     secs = utime.time()
  61.     cTime = utime.localtime(secs + sGMT)                # calculate the current datetime considering above
  62.  
  63.  
  64.     month = cTime[1]
  65.     day = cTime[2]
  66.     hour = cTime[3]
  67.     minute = cTime[4]
  68.     second = cTime[5]
  69.  
  70.     if int(month) < 10:
  71.         months = "0" + str(month)
  72.     else:
  73.         months = month
  74.  
  75.     if int(day) < 10:
  76.         days = "0" + str(day)
  77.     else:
  78.         days = day
  79.  
  80.     if int(hour) < 10:                                  # Convert time to be 03:09:02 instead of 3:9:2
  81.         hours = "0" + str(hour)
  82.     elif int(hour) == 24:                               # Hour can has values from 0...23
  83.         hours = "00"
  84.     else:
  85.         hours = hour
  86.  
  87.     if int(minute) < 10:
  88.         minutes = "0" + str(minute)
  89.     else:
  90.         minutes = minute
  91.    
  92.     if int(second) < 10:
  93.         seconds = "0" + str(second)
  94.     else:
  95.         seconds = second
  96.    
  97.     # Create current time in format: YYYY-MM-DD HH:MM:SS
  98.     currentTime = "{}-{}-{} {}:{}:{}".format(cTime[0], months, days, hours, minutes, seconds)
  99.  
  100.     return currentTime
  101.  
  102. def buildjson(temp, hum, error, error_desc):
  103.     currentTime = getCurrentDatetime()
  104.  
  105.     x = {
  106.             "location": location,
  107.             "temperature": temp,
  108.             "humidity": hum,
  109.             "time": currentTime,
  110.             "error": (error, error_desc),
  111.             "save2db": save2db
  112.         }
  113.  
  114.     return ujson.dumps(x)
  115.  
  116. def getData(sensor):
  117.  
  118.     if debug: write2debug('Inside getData')
  119.     try:
  120.        
  121.         temp = []
  122.         humi = []
  123.         for x in range(nom):                                   # Make n measurements and calculate median from them
  124.             sleep(dbr)                                         # Give sensore some time to prepare
  125.             sensor.measure()                                   # Poll sensor
  126.             if debug: write2debug('Sensor poll')
  127.             t = sensor.temperature()
  128.             h = sensor.humidity()
  129.             if isinstance(t, float) and isinstance(h, float):  # Confirm sensor results are numeric
  130.                 temp.append(t)
  131.                 humi.append(h)
  132.             else:
  133.                 if debug: write2debug('Invalid sensor reading. Publishing error to mosquitto.')
  134.                 msg = buildjson(None, None, True, 'Invalid sensor readings.')
  135.                 client.publish(topic, bytes(msg, 'utf-8'))      # Publish sensor data to MQTT topic
  136.                 if debug: write2debug('error published.')
  137.                
  138.  
  139.         temperature = median(temp)
  140.         humidity = median(humi)
  141.  
  142.         msg = buildjson(temperature, humidity, False, "")
  143.         if debug: write2debug('json build. Publishing data to mosquitto.')
  144.         client.publish(topic, bytes(msg, 'utf-8'))              # Publish sensor data to MQTT topic
  145.         if debug: write2debug('data published.')
  146.     except OSError:
  147.         msg = buildjson(None, None, True, 'Failed to read sensor.')
  148.         client.publish(topic, bytes(msg, 'utf-8'))              # Publish sensor data to MQTT topic
  149.         if debug: write2debug('Failed to read sensor.')
  150.  
  151. def sub_cb(t, msg):
  152.  
  153.     if debug: write2debug('Inside sub_cb')
  154.     if debug: write2debug('topic received=' + t.decode("utf-8")  + ', topic defined=' + topic.decode("utf-8"))
  155.     if t.decode("utf-8") == topic.decode("utf-8") :
  156.         print((t, msg))
  157.         if debug: write2debug('msg received: ' + msg.decode("utf-8"))      # bytes to string
  158.         client.disconnect()
  159.         deep_sleep(dsleep*1000)
  160.  
  161. def write2debug(message):
  162.     with open('debug.log', 'a') as f:
  163.         f.write(message+'\n')
  164.  
  165.  
  166. client = MQTTClient(client_id, server, port=8883, user=b'username', password=b'password', ssl=True, ssl_params={'key':key_data, 'cert':cert_data})
  167.  
  168. client.set_callback(sub_cb)                             # wait until data is published onto broker before putting into deep sleep
  169. client.connect()                                        # Connect to MQTT broker
  170.  
  171. client.subscribe(topic)
  172. if debug: write2debug('Client connected and subcribed to topic')
  173.  
  174. sensor = DHT22(Pin(5, Pin.IN, Pin.PULL_UP))             # DHT-22 on GPIO 5 (input with internal pull-up resistor)
  175. if debug: write2debug('Sensor data read')
  176.  
  177. if debug: write2debug('Entering getData ')
  178. getData(sensor)
  179. if debug: write2debug('Done with getData ')
  180.  
  181. while True:
  182.     client.check_msg()
  183.     sleep(1)
  184.  
  185.  
  186.