from machine import Pin
import dht, time, urequests, ubinascii

SID = 'ACbb42cd647f987a9b76c211cbac55d257'
TOKEN = '8f704d000b1f2837ab68ed8565b8face'
F_NUMBER = "whatsapp:+14155238886"
T_NUMBER = "whatsapp:+50497992710"

sensor = dht.DHT22(Pin(23))

auth = ubinascii.b2a_base64(f'{SID}:{TOKEN}'.encode()).decode().strip()
lib = 'http://api.twilio.com/2010-04-01/Accounts/{}/Messages.json'.format(SID)

def enviarWhatsApp(mensaje):
  headers = {
        'Authorization': 'Basic ' + auth
        }
  data = {
        'From': F_NUMBER,
        'To': T_NUMBER,
        'Body': mensaje
        }
    
  response = urequests.post(lib, headers=headers, data=data)
  print('Respuesta:', response.text)
  response.close()

while True:
    sensor.measure()
    time.sleep(2)
    temp = sensor.temperature()
    hum = sensor.humidity()

    datos = f'TEMP: {temp}°C - HUMEDAD: {hum}%'
    print(datos)

    try:
      enviarWhatsApp(datos)
    except Exception as error:
      print("Error al enviar mensaje:",error)
    
    time.sleep(15)