In the following code i'm trying to access the Bew Page, but i'm not able to do that. please help me to find where the problem exactly is
from machine import ADC, Pin
import utime
import network
import time
import socket
import uasyncio as asyncio
from picozero import pico_temp_sensor
import os
soil = ADC(Pin(28))
pump = Pin(5, Pin.OUT)
min_moisture = 15971
max_moisture = 44458
prev_value = 0
read_delay = 1
current_file = None
pump_state = "off"
save_interval = 0.5
factor = 0.05
vsys_adc = ADC(Pin(26))
R1 = 1000
R2 = 1000
voltage_divider_ratio = R2 / (R1 + R2)
moisture = 0
vsys_voltage_value = 0
temperature = 0
ssid = '***********'
password = '******************'
wlan = network.WLAN(network.STA_IF) #network.WLAN object is configured as a station (client) interface
network.hostname("pico")
here is the html code
HTML = """\ #html
<!DOCTYPE html>
<html>
<head>
<title>Irrigation System</title>
</head>
<body>
<h1>Smart Irrigation System</h1>
<p>Moisture: {moisture}%</p>
<p>Temperature: {temperature} C</p>
<p>Battery Voltage: {voltage} V</p>
<p>Pump State: {pump_state}</p>
<button onclick="fetch('/pump/on')">Turn Pump ON</button>
<button onclick="fetch('/pump/off')">Turn Pump OFF</button>
</body>
</html>
"""
**here is connecting to the network**
def connect_to_network(): #connect to network
wlan.active(True) #activate the wireless LAN interface
wlan.config(pm = 0xa11140) #pwoer management: always on
wlan.connect(ssid, password)
max_wait = 10 #representing the maximum number of seconds to wait for the connection
while max_wait > 0: #The while loop runs as long as max_wait is greater than 0, meaning that there is still time left to wait for the connectio
if wlan.status() < 0 or wlan.status() >= 3: #If the status is less than 0 (indicating an error) or greater than or equal to 3 (indicating a successful connection)
break #break out of the loop
max_wait -= 1
print('waiting for connection...')
time.sleep(1)
if wlan.status() != 3:
raise RuntimeError('network connect failed')
else:
print('connected')
status = wlan.ifconfig()
print('ip = ' + status[0])
**and here is the serve client function**
async def serve_client(reader, writer): #webserver
print("Got a request")
request_line = await reader.readline()
method, path, _ = request_line.split(b" ")
print("Method: ", method)
print("Path: ", path)
if method == b"GET" and path == b"/":
# Read the latest measurements
moisture = await read_moisture_measurement()
temperature = await read_temperature()
voltage = await read_battery_voltage()
pump_state = pump.value()
# Generate the HTML response
response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"
response += HTML.format(moisture=moisture, temperature=temperature, voltage=voltage, pump_state=pump_state)
await writer.awrite(response.encode())
elif method == b"GET" and path == b"/pump/on":
pump.on() # Turn pump on
response = "HTTP/1.1 200 OK\r\n\r\nPump turned on"
await writer.awrite(response)
elif method == b"GET" and path == b"/pump/off":
pump.off() # Turn pump off
response = "HTTP/1.1 200 OK\r\n\r\nPump turned off"
await writer.awrite(response)
else:
response = "HTTP/1.1 404 NOT FOUND\r\n\r\nPage Not Found"
await writer.awrite(response)
await writer.aclose()
def format_timestamp(timestamp):
tm = utime.localtime(timestamp)
return "{:04d}_{:02d}_{:02d}_{:02d}_{:02d}_{:02d}".format(tm[0], tm[1], tm[2], tm[3], tm[4], tm[5])
def measurement_filter(basic_value, factor): #This function applies a filter to the given basic_value using the previous value and a factor
filtered_moisture=basic_value * factor + prev_value * (1-factor)
prev_moisture = filtered_moisture
return filtered_moisture
**Measuremnt**
async def read_moisture_measurement():
raw_moisture = (max_moisture - soil.read_u16()) * 100 / (max_moisture - min_moisture)
moisture = measurement_filter(raw_moisture, factor)
return moisture
async def read_temperature():
temperature = pico_temp_sensor.temp
return temperature
async def read_battery_voltage():
vsys_voltage_value = vsys_adc.read_u16() * 3.3 / voltage_divider_ratio / 65535
return vsys_voltage_value
class StoreMeasurement:
def __init__(self):
self.moisture = None
self.temperature = None
self.battery_voltage = None
self.pump_state = None
async def control_water_pump(moisture, pump_on_time, pump_needs_reset):
pump_on_time = 0
pump_timeout = 10
current_time = utime.time()
# If moisture level is low and pump doesn't need a reset
if moisture < 30 and not pump_needs_reset:
# If pump is not already turned on
if not pump.value():
pump.on()
pump_on_time = current_time
# If moisture level is high
elif moisture >= 80:
# If pump is turned on
if pump.value():
pump.off()
pump_on_time = 0
# Reset the pump only if it has run for at least pump_timeout seconds
if current_time - pump_on_time >= pump_timeout:
pump_needs_reset = True
# If pump is turned on and running for more than pump_timeout seconds
if pump.value() and current_time - pump_on_time >= pump_timeout:
pump.off()
pump_on_time = 0
pump_needs_reset = True # Prevent the pump from turning on until the moisture level reaches 80%
return pump_on_time, pump_needs_reset
async def save_measurement_to_file(data):
global current_file, current_file_creation_time
manage_files()
timestamp = utime.time()
formatted_timestamp = format_timestamp(timestamp)
current_file.write(f'{formatted_timestamp};{str(round(data.moisture, 2)).replace(".", ",")};{str(round(data.temperature, 2)).replace(".", ",")};{str(round(data.vsys_voltage_value, 2)).replace(".", ",")};{data.pump_state}\n')
def manage_files():
global current_file, current_file_creation_time
current_time = utime.time()
if current_file is None or current_time - current_file_creation_time >= 3600:
if current_file is not None:
current_file.close()
current_timestamp = format_timestamp(current_time)
file_name = current_timestamp + '.csv'
current_file = open(file_name, 'w')
current_file.write("Timestamp;Moisture;Temperature;Voltage;State\n")
current_file_creation_time = current_time
file_list = [f for f in os.listdir() if f.endswith('.csv')]
if len(file_list) > 24:
file_list.sort()
oldest_file_name = file_list[0]
os.remove(oldest_file_name)
async def irrigation_task():
#global moisture, temperature, vsys_voltage_value, irrigation_log
data = StoreMeasurement()
pump_on_time = 0
pump_needs_reset = False
while True:
data.moisture = await read_moisture_measurement()
data.temperature = await read_temperature()
data.vsys_voltage_value = await read_battery_voltage()
print(f'Moisture: {data.moisture:.2f}, Temperature: {data.temperature:.2f}, Battery Voltage: {data.vsys_voltage_value:.2f}')
pump_on_time, pump_needs_reset = await control_water_pump(data.moisture, pump_on_time, pump_needs_reset)
data.pump_state = pump.value()
await save_measurement_to_file(data)
await asyncio.sleep(read_delay)
async def webserver_task():
server = await asyncio.start_server(serve_client, "0.0.0.0", 80)
while True:
await asyncio.sleep(read_delay)
async def main():
connect_to_network()
irrigation_handeler = asyncio.create_task(irrigation_task())
print("irrigation_task:", irrigation_task)
webserver_handeler = asyncio.create_task(webserver_task())
print("Webserver started on {}:{}".format(wlan.ifconfig()[0], 80))
await asyncio.gather(irrigation_handeler, webserver_handeler)
asyncio.run(main())
it's a smart Irrigation System Micropython Code. this code is running on a raspberry pi pico W. I want to implement a Web Server serve a web page, via the web page i must be able to control the water pump manually, and i must display the Measurements.