Problem with zero length responses (solved)
Problem with zero length responses (solved, I think.)
Ther piuco server was getting a [''] from chrome about every minute. This went into the parsing routines that threw up errors. So wrote an if statement to avoid this. Got confused about types eg byes vrs string for a while but think this is now cracked. Have a good stub for working client interface, bensensor4.html,, while on NAME AP network generated by micropython code called bensense3.py. All buttons, radio buttons and the textbox are working. Here's a photo of typical interaction:
Note on bottom left a zero length response just leaves a msg but does not enter into parsing. (On 'original' size you can read all the screen text.
---------------below is bensense3.py---------------------
#Worked ok Tue Aug 6 11:04:01 NZST 2024. Can't get other mode to work Will play with this one.
import network
import time
import socket
from machine import Pin
import parse_request1 #added this frim perplexity
# led = Pin(25, Pin.OUT)
# led.off()
# led.on()
led = machine.Pin("LED", machine.Pin.OUT)
#led.off()
led.on()
# def web_page():
# html = """<html><head><meta name="viewport" content="width=device-width, initial-scale=1"></head>
# <body><h1>Hello 33w21World</h1></body></html>
# """
# return html
#todo make this HTML into separate file
# if you do not see the network you may have to power cycle
# unplug your pico w for 10 seconds and plug it in again
def ap_mode(ssid, password):
"""
Description: This is a function to activate AP mode
Parameters:
ssid[str]: The name of your internet connection
password[str]: Password for your internet connection
Returns: Nada
"""
# file = open("simpleled.html")
# html = file.read()
# file.close()
# Just making our internet connection
stateis ='Starting up'
ap = network.WLAN(network.AP_IF)
ap.config(essid=ssid, password=password)
ap.active(True)
while ap.active() == False:
pass
print('AP Mode Is Active, You can Now Connect')
print('IP Address To Connect to:: ' + ap.ifconfig()[0])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #creating socket object
s.bind(('', 80))
s.listen(5)
while True:
conn, addr = s.accept()
print('Got a connection from %s' % str(addr))
request = conn.recv(1024)
#print('Content received by Pico = %s' % str(request))
print("TTTTTType of request = ",type(request))
print("LLLLlength of request = ",len(request))
# In your main loop, replace the print statement with:
print('Content received by Picoooo:')
#response = web_page()
#new---
#print("RRRRR" + request.method)
if len(request) > 0:
print(parse_request1.parse_request(request))
request = str(request)
#led_on = request.find('/light/on')
#led_off = request.find('/light/off')
led_on = request.find(' /ledon') #the space is important
led_off = request.find(' /ledoff')
print( 'led on = ' + str(led_on))
print( 'led off = ' + str(led_off))
#---finish new---got -1 for off and 308 for on--
#new new--
#todo sort out indenting. Better to do != -1
#if led_on > 0:
if led_on != -1:
print("led on")
led.value(1)
stateis = "LED is ON"
if led_off != -1:
print("led off")
led.value(0)
stateis = "LED is OFF"
file = open("bensensor4.html")
#file = open("index.html")
html = file.read()
file.close()
html2 = html.replace('**ledState**', stateis)
print(stateis)
response=html2 #new
conn.send(response)
conn.close()
#s.close() #Try this !!
ap_mode('NAME',
'PASSWORD')
#todo put -->html = html.replace('**ledState**', led_state_text) before line 79
import network
import time
import socket
from machine import Pin
import parse_request1 #added this frim perplexity
# led = Pin(25, Pin.OUT)
# led.off()
# led.on()
led = machine.Pin("LED", machine.Pin.OUT)
#led.off()
led.on()
# def web_page():
# html = """<html><head><meta name="viewport" content="width=device-width, initial-scale=1"></head>
# <body><h1>Hello 33w21World</h1></body></html>
# """
# return html
#todo make this HTML into separate file
# if you do not see the network you may have to power cycle
# unplug your pico w for 10 seconds and plug it in again
def ap_mode(ssid, password):
"""
Description: This is a function to activate AP mode
Parameters:
ssid[str]: The name of your internet connection
password[str]: Password for your internet connection
Returns: Nada
"""
# file = open("simpleled.html")
# html = file.read()
# file.close()
# Just making our internet connection
stateis ='Starting up'
ap = network.WLAN(network.AP_IF)
ap.config(essid=ssid, password=password)
ap.active(True)
while ap.active() == False:
pass
print('AP Mode Is Active, You can Now Connect')
print('IP Address To Connect to:: ' + ap.ifconfig()[0])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #creating socket object
s.bind(('', 80))
s.listen(5)
while True:
conn, addr = s.accept()
print('Got a connection from %s' % str(addr))
request = conn.recv(1024)
#print('Content received by Pico = %s' % str(request))
print("TTTTTType of request = ",type(request))
print("LLLLlength of request = ",len(request))
# In your main loop, replace the print statement with:
print('Content received by Picoooo:')
#response = web_page()
#new---
#print("RRRRR" + request.method)
if len(request) > 0:
print(parse_request1.parse_request(request))
request = str(request)
#led_on = request.find('/light/on')
#led_off = request.find('/light/off')
led_on = request.find(' /ledon') #the space is important
led_off = request.find(' /ledoff')
print( 'led on = ' + str(led_on))
print( 'led off = ' + str(led_off))
#---finish new---got -1 for off and 308 for on--
#new new--
#todo sort out indenting. Better to do != -1
#if led_on > 0:
if led_on != -1:
print("led on")
led.value(1)
stateis = "LED is ON"
if led_off != -1:
print("led off")
led.value(0)
stateis = "LED is OFF"
file = open("bensensor4.html")
#file = open("index.html")
html = file.read()
file.close()
html2 = html.replace('**ledState**', stateis)
print(stateis)
response=html2 #new
conn.send(response)
conn.close()
#s.close() #Try this !!
ap_mode('NAME',
'PASSWORD')
#todo put -->html = html.replace('**ledState**', led_state_text) before line 79
-------------------below is parse_request.py----gets called above---------
def parse_request(request):
# Decode the bytes to a string
request_str = request.decode('utf-8')
# Split the request into lines
lines = request_str.split('\r\n')
print(lines)
# Parse the first line (request line)
method, path, protocol = lines[0].split(' ')
# Parse headers
headers = {}
for line in lines[1:]:
if ':' in line:
key, value = line.split(':', 1)
headers[key.strip()] = value.strip()
# Parse query parameters
query_params = {}
if '?' in path:
path, query_string = path.split('?', 1)
params = query_string.split('&')
for param in params:
if '=' in param:
key, value = param.split('=')
query_params[key] = value
# Format the parsed data
formatted_request = f"Method: {method}\n"
formatted_request += f"Path: {path}\n"
formatted_request += f"Protocol: {protocol}\n"
formatted_request += "Headers:\n"
for key, value in headers.items():
formatted_request += f" {key}: {value}\n"
if query_params:
formatted_request += "Query Parameters:\n"
for key, value in query_params.items():
formatted_request += f" {key}: {value}\n"
return formatted_request
---------------below is bensensor4.html-----used in bensense3.py----------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ben Sensor</title>
</head>
<body>
<h1>bensensor0</h1>
Led status is **ledState**
{{text}}
<p>Choose an LED pattern:</p> <!--<form action="/" method="POST"> -->
<form action="/">
<label>Enter the text to scroll</label>
<input type="text" name="text" />
<button type="submit" value="Login">Submit</button>
</form>
<form action="/action_page.php">
<p>Please select your favorite Web language:</p>
<input type="radio" id="html" name="fav_language" value="HTML">
<label for="html">HTML</label><br>
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">CSS</label><br>
<input type="radio" id="javascript" name="fav_language" value="JavaScript">
<label for="javascript">JavaScript</label>
<br>
<p>Please select your age:</p>
<input type="radio" id="age1" name="age" value="30">
<label for="age1">0 - 30</label><br>
<input type="radio" id="age2" name="age" value="60">
<label for="age2">31 - 60</label><br>
<input type="radio" id="age3" name="age" value="100">
<label for="age3">61 - 100</label><br><br>
<input type="submit" value="Submit">
</form>
<p>Click the buttons to control the LED</p>
<input type="button" onclick="document.location='/ledon'" value="TURN LED ON1"/>
<p></p>
<input type="button" onclick="document.location='/ledoff'" value="TURN LED OFF"/>
<p></p>
<p>The LED is **ledState**</p>
<p>The internal Pico temperature is **TEMP**</p>
</body>
</html>
---------------------------------------I got most of this from w3scools and cyberdog---------
Comments
Post a Comment