# SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries
# SPDX-License-Identifier: MIT

import os
import sys
import time
import ssl
import wifi
import socketpool
import microcontroller
import board
import busio
import adafruit_requests
#import adafruit_ahtx0
import adafruit_dht
from adafruit_io.adafruit_io import IO_HTTP, AdafruitIO_RequestError
from microcontroller import cpu

def readDHTSensor():
	runFlag = True 
	while runFlag:
		try:
			# Print the values to the serial port
			temperature_c = dhtDevice.temperature
			temperature_f = temperature_c * (9 / 5) + 32
			humidity = dhtDevice.humidity
			print(
				"Temp: {:.1f} F / {:.1f} C    Humidity: {}% ".format(
					temperature_f, temperature_c, humidity
				)
			)
			runFlag = False
	
		except RuntimeError as error:
			# Errors happen fairly often, DHT's are hard to read, just keep going
			print(error.args[0])
			time.sleep(2.0)
			continue
		except Exception as error:
			dhtDevice.exit()
			raise error

	return [temperature_f, humidity, temperature_c]

# Initial the dht device, with data pin connected to:
dhtDevice = adafruit_dht.DHT11(board.GP4)



wifi.radio.connect(os.getenv('CIRCUITPY_WIFI_SSID'), os.getenv('CIRCUITPY_WIFI_PASSWORD'))

aio_username = os.getenv('ADAFRUIT_IO_USERNAME')
aio_key = os.getenv('ADAFRUIT_IO_KEY')

pool = socketpool.SocketPool(wifi.radio)
requests = adafruit_requests.Session(pool, ssl.create_default_context())
# Initialize an Adafruit IO HTTP API object
io = IO_HTTP(aio_username, aio_key, requests)
print("connected to io")

#  use Pico W's GP0 for SDA and GP1 for SCL
#i2c = busio.I2C(board.GP1, board.GP0)
#aht20 = adafruit_ahtx0.AHTx0(i2c)

try:
# get feed
    picowTemp_feed = io.get_feed("mytemperature")
    picowHumid_feed = io.get_feed("myhumidity")
except AdafruitIO_RequestError:
# if no feed exists, create one
    print("Feed error")
    sys.exit(-1)

#  pack feed names into an array for the loop
feed_names = [picowTemp_feed, picowHumid_feed]
print("Connected to feeds.")

clock = 300


while True:
    try:
        #  when the clock runs out..
        if clock > 50:
            print("") # Prints a blank line after clock print.
            #  read sensor
            dhtData = readDHTSensor()
            data = [dhtData[0], dhtData[1]]
            #  send sensor data to respective feeds
            for z in range(2):
                io.send_data(feed_names[z]["key"], data[z])
                print("sent %0.1f" % data[z])
                time.sleep(1)
            #  print sensor data to the REPL
            print("\nTemperature: %0.1f C" % data[0])
            print("Humidity: %0.1f %%" % data[1])
            print()

            time.sleep(1)
            #  reset clock
            clock = 0
        else:
            clock += 1
    # pylint: disable=broad-except
    #  any errors, reset Pico W
    except Exception as e:
        print("Error:\n", str(e))
#        print("Resetting microcontroller in 10 seconds")
        time.sleep(3)
#        microcontroller.reset()
    #  delay
    time.sleep(1)
#    print(clock)
    print(clock,end=" ")
