# Connect to the WiFi (WIFI連線) def connect_wifi(ssid, password): wlan = network.WLAN(network.STA_IF) wlan.active(True) if not wlan.isconnected(): wlan.connect(ssid, password) while not wlan.isconnected(): pass
# Update the time from NTP server (更新時間) def update_time(): ntptime.host = 'pool.ntp.org' ntptime.settime() tm = utime.localtime(utime.mktime(utime.localtime()) + 28800) rtc.datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))
# Get current time(取得目前時間) def get_time(): time = rtc.datetime() current_hour = time[4] current_minute = time[5] current_second = time[6] current_time = "{:02d}:{:02d}:{:02d}".format(current_hour, current_minute, current_second) return current_time, current_hour, current_minute
# Send data to IFTTT (傳資料到IFTTT) def send_to_ifttt(url, soil_temp, soil_vwc, state): data = {'value1': str(soil_temp), 'value2': str(soil_vwc), 'value3': state} request_headers = {'Content-Type': 'application/json'} request = urequests.post(url, json=data, headers=request_headers) request.close()
def main(): state = " Normal " connect_wifi(wifi_ssid, wifi_password) update_time() # update the time from NTP server at the start lcd.putstr("WIFI is connected!")
# setting the initial time to a value that triggers the first send last_sent_hour = -1 last_sent_minute = -1 line_flag = False
while True: current_time, current_hour, current_minute = get_time() # read sensor every 15 minutes (每15分鐘上傳數值到Google Sheets)
if current_minute % 15 == 0 and current_minute != last_sent_minute: soil_temp, soil_vwc = Sensor_Access() send_to_ifttt(IFTTT_URL_GOOGLE_SHEET, soil_temp, soil_vwc, state)
last_sent_minute = current_minute
# send to LINE sheet once every day at 7:00pm (每晚七點上傳數值到LINE) if current_hour == 19 and current_minute == 0 and line_flag == False: soil_temp, soil_vwc = Sensor_Access() #send_to_ifttt(IFTTT_URL_GOOGLE_SHEET, soil_temp, soil_vwc, state) send_to_ifttt(IFTTT_URL_LINE, soil_temp, soil_vwc, state) line_flag = True
# reset line_flag after 7:00pm (重置line_flag)
if current_hour == 19 and current_minute > 0:
line_flag = False
# send to LINE when soil_vwc is between 0 and 10 (當淹水時會發緊報)
soil_temp, soil_vwc = Sensor_Access() if 0 < soil_vwc <= 10: state = " ALERT!! " send_to_ifttt(IFTTT_URL_LINE, soil_temp, soil_vwc, state) send_to_ifttt(IFTTT_URL_GOOGLE_SHEET, soil_temp, soil_vwc, state) else: state = " Normal "
# print on LCD every second (LCD每秒更新一次顯示畫面) lcd_print(current_time, soil_vwc) print(current_time, soil_vwc) utime.sleep(1) # sleep for 1 second