from machine import Pin, ADC, PWM
from time import sleep
import time
import ifttt
import network
import dht
import wifi 
from umqtt.simple import MQTTClient
from machine import SoftI2C
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
import thing_speak as tsp

ssid = 'Wokwi-GUEST'
password = ''


d = dht.DHT22(Pin(12, Pin.IN))
motion = Pin(12, Pin.IN)


h = -1
t = -1



def connect_internet():
  print("Connecting to WiFi", end="")
  sta_if = network.WLAN(network.STA_IF)
  sta_if.active(True)
  sta_if.connect(ssid, password)
  while not sta_if.isconnected():
    print(".", end="")
    time.sleep(0.1)
  print(" Connected!")

def thingspeak_display():
    d.measure()
    t = d.temperature()
    h = d.humidity()
    print("Update to thingspeak....")
    tsp.update_temp_and_hum(t, h)
    
def send_email():   
    d.measure()
    t = d.temperature()
    h = d.humidity()
    
    if(t >= 30):
      ifttt.alert_motion(t)
      print("sent email")

def send_to_ggsheet():   
    d.measure()
    t = d.temperature()
    h = d.humidity()
    
    if(t >= 30):
      ifttt.send_to_sheet(t)
      print("sent")
import gc

if __name__ == "__main__":
  connect_internet()
  last_thingspeak_display=time.time()
  while True:
    current_time= time.time()
    if current_time - last_thingspeak_display >= 10:
      send_to_ggsheet()
      print(gc.mem_free())
      last_thingspeak_display = current_time