import urequests
import gc
from machine import Pin, ADC, I2C, RTC, Timer, SoftI2C
import network
from time import sleep, sleep_ms, ticks_ms, ticks_diff
import utime, time
import esp
#from bh1750 import BH1750
from struct import unpack as unp
import ntptime
import dht
import data2gsheet
esp.osdebug(None)
gc.collect()
def wifi_connect():
ssid = "Wokwi-GUEST"
password = ""
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect("Wokwi-GUEST", " ")
while station.isconnected() == False:
pass
print('Connection successful')
########### Time zone info ################
TZ_INFO = "UTC7"
########### Time zone info ################
######## Google Apps Script ID #############
#GAS_ID = "AKfycbyu1NkECJ11LjIYtgGtYRy5-qu2kIiK7ilW_unpTygZb-3o8EfG2IECpJco4Wp0AI3v" # Google Script id from deploy app >>> Deployment ID:
GAS_ID = "AKfycbwm4OqMNSIQwGFiKbNz4n5xMBNIEe3MasxMieswUsn9GaNxMfPtZO4z0VuD6bEhQwea" # Farm2
######## Google Apps Script ID #############
########### Function to send data to Google Sheet ################
def send_data_to_ggsheet(temp, humi, light, soilmc):
global GAS_ID
temp, humi, light, soilmc = read_sensor()
print(("Temperature: {} °C, Humidity: {} %RH, Light: {} lux, SoilMC: {} %\n".format(temp, humi, light, soilmc)))
url = "https://script.google.com/macros/s/" + GAS_ID + "/exec?"
data = "temp=" + str(temp) + "&humi=" + str(humi) + "&light=" + str(light) + "&soilmc="+ str(soilmc)
url_data = url+data
print("Posting Temperature, Humidity, Light Intensity and soil MC data to Google Sheet")
try:
response = urequests.get(url_data)
response.raise_for_status() # Raises an HTTPError if the HTTP request returned an unsuccessful status code
print("HTTP Status Code:", response.status_code)
payload = response.text
print("Payload:", payload)
print("Temperature: %d°C, Humidity: %d%%, Light: %d%%, SoilMC: %d%%" % (temp, humi, light, soilmc))
except urequests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
except Exception as err:
print(f"Other error occurred: {err}")
########### Function to send data to Google Sheet ################
last_message = 0
message_interval = 30 #
########### Function to send data to Google Sheet ################
sensor = dht.DHT22(Pin(4))
def read_sensor():
try:
sensor.measure()
temp = sensor.temperature()
humi = sensor.humidity()
light = 12354
soilmc = 75.35
print(f'temperature: {temp} C humidity: {humi} Light: {light} lux, SoilMC: {soilmc} %')
return temp, humi, light, soilmc
except OSError as e:
return('Failed to read sensor.')
wifi_connect()
while True:
try:
if (time.time() - last_message) > message_interval:
temp, humi, light, soilmc = read_sensor()
send_data_to_ggsheet(temp, humi, light, soilmc)
last_message = time.time()
print("data sending ...")
except OSError as e:
restart_and_reconnect()