from machine import Pin, Timer
import network
import urequests # for http  API
import time
#from umqtt.robust import MQTTClient # for MQTT Broker
import sys
#import dht
from dht import DHT22

dht22 = DHT22(Pin(12))

# Function to read DHT
def readDht():
    dht22.measure()
    return dht22.temperature(), dht22.humidity()
    # test DHT function
print (readDht())

# Split Sensor reading..
#temp, hum = readDht()

# Connect with WiFi
import network
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""

# Function to connect to local WiFi

def connect_wifi():
    wifi = network.WLAN(network.STA_IF)
    wifi.active(True)
    wifi.disconnect()
    wifi.connect(WIFI_SSID,WIFI_PASSWORD)
    if not wifi.isconnected():
        print('connecting..')
        timeout = 0
        while (not wifi.isconnected() and timeout < 10):
            print(10 - timeout)
            timeout = timeout + 1
            time.sleep(1) 
    if(wifi.isconnected()):
        print('connected')
    else:
        print('not connected')
        sys.exit()
    print('network config:', wifi.ifconfig())
        
connect_wifi() # Connecting to WiFi Router 

# Thingspeak HTTP API Protocol (Connection)

HTTP_HEADERS = {'Content-Type': 'application/json'} 
THINGSPEAK_WRITE_API_KEY = '0OSO0NUPZ5X35R62' # Write API of the Channel

while True:
    time.sleep(5) 
    
    #pin = Pin(12, Pin.OUT, Pin.PULL_DOWN) #Rpi
    dht22 = DHT22(Pin(12)) #DHT22 object created at Pin 12
    dht22.measure()
    print("Temperature: {}".format(dht22.temperature()))
    print("Humidity: {}".format(dht22.humidity()))
    
    Temp  = dht22.temperature() # store dht22 temperature into temp variable
    Hum = dht22.humidity()

    dht_readings = {'field1':Hum, 'field2':Temp} 
    request = urequests.post( 'http://api.thingspeak.com/update?api_key=' + THINGSPEAK_WRITE_API_KEY, json = dht_readings, headers = HTTP_HEADERS )  
    request.close() 
    print(dht_readings) 
    print(" Msg sent to Thingspeak channel successfully...")
    print(" ********************************************")


'''



# MQTT Protocol 

#Connect with ThingSpeak via MQTT Protocol .
#The MQTT protocol is supported in a built-in library in the Micropython binaries 
#-- this protocol can be used send data from your ESP32, over WIFI, to a free cloud database
# Configurate & Initiate ThingSpeak Channel and MQTT


from umqttsimple import MQTTClient
mqtt_client_id  = bytes('client_'+'12321', 'utf-8') # Just a random client ID
# ThingSpeak Credentials:

SERVER = "mqtt.thingspeak.com"
#mqtt_server = "mqtt,thingspeak.com"
CHANNEL_ID = "2226861"
WRITE_API_KEY = "4ZV4EMSFR3A0EPRL"
PUB_TIME_SEC = 30  

# Connect MQTT Broker

client = MQTTClient(client_id=mqtt_client_id, 
                    server=SERVER, 
                    user=None, 
                    password=None,
                    ssl=False)
                   
try:            
    client.connect()
except Exception as e:
    print('could not connect to MQTT server {}{}'.format(type(e).__name__, e))
    sys.exit()

#client = MQTTClient("umqtt_client", SERVER)
# Create the topic string
topic = "channels/" + CHANNEL_ID + "/publish/" + WRITE_API_KEY
# Read Sensors
temp, hum = readDht()
# Create a payload based on your Channel fields
#payload = "field1="+str(temp)+"&field2="+str(hum)+"&field3="+str(extTemp)+"&field4="+str(lum)+"&field5
payload = "field1="+str(temp)+"&field2="+str(hum)
# Sending data to ThingSpeak one time for test 
client.connect()
client.publish(topic, payload)
client.disconnect() 
'''
esp:VIN
esp:GND.2
esp:D13
esp:D12
esp:D14
esp:D27
esp:D26
esp:D25
esp:D33
esp:D32
esp:D35
esp:D34
esp:VN
esp:VP
esp:EN
esp:3V3
esp:GND.1
esp:D15
esp:D2
esp:D4
esp:RX2
esp:TX2
esp:D5
esp:D18
esp:D19
esp:D21
esp:RX0
esp:TX0
esp:D22
esp:D23
dht1:VCC
dht1:SDA
dht1:NC
dht1:GND