File "Praktikum7.py"
Full Path: /var/www/html/main/lecture-notes/Internet of Things/02 Materi Praktikum - IoT - PDF/File Python/Praktikum7.py
File size: 2 KB
MIME-type: text/x-script.python
Charset: utf-8
from machine import Pin
import time
import network
import urandom as random
import urequests as requests
# Variabel Wi-Fi
SSID = "<SSID>"
Password = "<Password>"
reset = True
# Variabel Mesin
p0 = Pin(2, Pin.OUT)
blinker = 0
# WebHook URL
api_url = "https://maker.ifttt.com/trigger/ESP8266/with/key/jbcdhtdJkdzdBVKvuGtTpElBPUUtSG6bEMbv68Bz0Pq"
# Blink Pendek 50ms
def blinkPendek():
p0.value(0)
time.sleep_ms(100)
p0.value(1)
time.sleep_ms(100)
# Blink Normal 1s
def blinkNormal():
p0.value(0)
time.sleep(1)
p0.value(1)
time.sleep(1)
# Koneksi Wi-Fi
def connectWLAN():
wlan0 = network.WLAN(network.STA_IF)
if reset:
wlan0.active(True)
# Masukkan SSID dan Password
wlan0.connect(SSID, Password)
while not wlan0.isconnected():
wlan0.active(True)
pass
status = wlan0.isconnected()
ip_addr = wlan0.ifconfig()
return status,ip_addr
# Data Generator
def genData():
ph = random.getrandbits(12)%14
suhu = random.getrandbits(12)%38
rh = random.getrandbits(12)%100
return ph,suhu,rh
# Main Function
def main():
print(">> Memulai ESP826 ... ")
print(">> Menghubungkan ke {}".format(SSID))
status,ip_addr = connectWLAN()
if(status == True):
print("==>> Terhubung")
print("")
print(">> ESP8266 Mengambil Data Sensor ... ")
ph,suhu,rh = genData() # Seolah-olah Ambil Data Sensor
print("==>> Sukses")
print("")
print(">> ESP8266 Mengirim Data ke GMAIL via IFTTT WebHook")
print("==>> PH : {}, Suhu : {}, dan RH : {}".format(ph,suhu,rh))
data = {"value1":ph,"value2":suhu,"value3":rh}
resp = requests.post(api_url,json=data)
if(resp.status_code==200):
print("==>> Sukses")
blinkPendek()
else:
print("==>> Gagal")
blinkPanjang()
resp.close()
else:
print("==>> Gagal Terhubung")
main()