import network
import urequests

import json

from machine import Pin
import dht  #The DHT driver is implemented in software and works on all pins
from time import sleep, sleep_us

pinServo = Pin(15, Pin.OUT)
sensorDHT = dht.DHT22(Pin(4))
pinLED = Pin(2, Pin.OUT)

WiFi_SSID = "Wokwi-GUEST"   #isikan dengan ssid hotspot
WiFi_PASS = ""              #isikan dengan password hotspot
# URL_SetPoint = "https://esp32basecamp2024-default-rtdb.firebaseio.com/SetPoint.json"
# URL_DataSensor = "https://esp32basecamp2024-default-rtdb.firebaseio.com/DataSensor.json"

URL_SetPoint = "https://esp32firebase30sep2024-default-rtdb.firebaseio.com/SetPoint.json"
URL_DataSensor = "https://esp32firebase30sep2024-default-rtdb.firebaseio.com/DataSensor.json"

def connect_Jaringan():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect(WiFi_SSID, WiFi_PASS)
        while not wlan.isconnected():
            pass
        print('network config:', wlan.ifconfig())

def servo():
    pinServo.on()
    sleep_us(1000)
    pinServo.off()

    sleep(0.5)
    
    pinServo.on()
    sleep_us(2000)
    pinServo.off()

    sleep(0.5)

connect_Jaringan()

while True:
    response1 = urequests.get(URL_SetPoint)              #ambil data
    SetPoint = json.loads(response1.text)
    print("Setpoint: ", SetPoint)
    SetPointTemperature = SetPoint['Temperature']
    response1.close()

    try:
        sensorDHT.measure() # ambil data
    except:
        pass
        
    temp = sensorDHT.temperature()
    hum = sensorDHT.humidity()

    Data = {"Temperature":temp, "Humidity":hum}
    JsonData = json.dumps(Data)
    response2 = urequests.patch(URL_DataSensor, data = JsonData)    #kirim data (non historical)
    # response2 = urequests.post(URL_DataSensor, data = JsonData)   #kirim data (historical)
    print(JsonData)
    response2.close()

    if (temp >= SetPointTemperature):
        pinLED.on()
        servo()
    else:
        pinLED.off()
$abcdeabcde151015202530fghijfghij