Posts

Showing posts from August, 2024

Problem with zero length responses (solved)

Image
 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...

Getting better at html forms for Ben wbserver

Image
 bensens2.py with associated bensensor3.html good start for coming BEN network. Took bits from kevsrobots cyberdog and bits from w3schools to give interaction below: bensense2.py is: #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 # 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): ...

Ben (Boardwalk Environment Network) Sensor Start

Image
 Start of bensensor. Idea is a box with Pi PicoW is put into boardwalk garden and records temperatures, humidity etc. Just logs them into iPhone comes near and an AP network established. The pico then becomes a webserver and uploads information to iPhone when it comes close, about 10m. Iphone uses browser to get to 192.168.4.1 and submits form so the pico responds with temperatures, logs, status, LEDs on/off etc. Can't get local AP network signals to get as far as PC from boardwalk garden so have to walk an iPhone or equivalent running Chrome to submit HTML for to pico server. Have proved most of the network operations but in bits and now need to have overall view of entire project and do it based on Perplexity advice. Certainly! Organizing multiple functionalities into a single server file on your Pico W is a great next step. Here's some general advice on structuring your project: ------------------------------ 1. **Route Handling**:    Create a system to handle differen...

Disappointing distance for AP network

 Don't think I can reach the boardwalk garden about 20m away with AP wifi. Went outside with iPhone and pressed html buttons in Chrome from code below. Works ok down the stairs but not where I park car. So I'm going to journal what I tried below and then go onto other options.. Code used: #Got this from https://www.perplexity.ai/search/i-m-using-the-python-requests-X_2r2DgcS1OF1_mnigU7qg #Idea is to send a text file generated by pico server. It logs x.log and produces reports x.txt. import network import socket num = 4956 # Set up access point ap = network. WLAN (network.AP_IF) ap. active ( False ) # Deactivate first #ap.config(essid=ssid, password=password) ap. config (essid= 'NAME' ,password= 'PASSWORD' ) print ( "Configured SSID:" , ap. config ( 'essid' )) ap. active ( True ) #ap.active(True) #ap.config(essid='PicoW_AP') # Wait for connection while not ap. isconnected (): pass print ( 'AP Mode Is Act...

Simple text sent to browser via AP picoW network

Image
 Simple text sent to browser via AP picoW network. Wanted just plain text, no HTML sent back to server on 192.168.4.1 Code used was as below:

Server sends back simple string from python request

Image
 Server sends back simple string from python request Want, for testing purposes to send back a simple string like "I'm in the led section of code" when the client sends path ending with /led, for instance. So just want to respond with Hello World sometimes rather than switch leds on and off, get temperature and get logs and report.txr. Below is hello World response. Have sent all the HTTP header stuff because it works but make want to have simpler way of sending a string. This worked.

Consolidating gains. ssid and sending text file and extending path with /x

Image
 Consolidating gains. ssid and sending text file and extending path with /x. Pi Pico network. It seems I can get the 'NAME' = ssid to work now. Also can send a path in the request from the PC's python client eg    requests.get('http://192.168.4.1 /leds' This means the pi pico server can sort requests into groups eg /leds , /text etc. Just as suggested by Perplexity. Here's the pic of python request from PC client getting text file back from server, even tho I put /leds in the path. (Should be text or something like that. Doesn't seem to be a real path, just like a parameter.)

Problem with ssid of Pi Pico network solved

 Been having problems with ssid of network Sent message below to Perplexity: I'm now having troble getting my Pi PicoW AP network to be recognized. Whatever I call it, the name of the network comes up as PICO241F. On the PC and on my iPhone. Below is the simplest initiation of an AP network that I can write but still get that strange 'PICO241F' name. Have tried resetting everything but not yet reinstalled micropython on my pi pico. This used to work but not now. Can you help me name my own Pi PIco network with my choice of ssid? #Want simplest AP network connection import network import socket ssid = 'NAME' #This gets changed to PICO24F password = 'PASSWORD' # Set up access point ap = network.WLAN(network.AP_IF) ap.active(True) ap.config(essid=ssid, password=password) # Wait for connection while not ap.isconnected():     pass print('AP Mode Is Active, You can Now Connect') print('IP Address To Connect to::', ap.ifconfig()[0]) #above all works...

SEnd text file via AP Pico network with nice formatted response.

Image
 Send text file via AP Pico network with nice formatted response. From perplexity I got this code to format responses nicely:(Worked. See screenshot of Thonny. 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') # 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_...

Led on, off via ap network and python request

Image
 Led on, off via ap network and python request Can't get micropython to .find '/ ledon' if sent by python on PC, so have changed parameters to Pledon and Pledoff. Works ok but now micropython server code not compatible with browser Chrome. To be fixed. It's that damn '/'.  Here's the newish micropython code from Thonny: ---------------------------------------------------------- #Now called WiFiSensor0.py from old WiFiAPLEDS3.py. Going to add internal temperature logging #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 machine # led = Pin(25, Pin.OUT) # led.off() # led.on() led = machine.Pin("LED", machine.Pin.OUT) #led.off() led.on() adcpin = 4 sensor = machine.ADC(adcpin) def ReadTemperature():   adc_value = sensor.read_u16()   volt = (3.3/65535) * adc_value   temperature = 27 - (volt - 0.706)/0.001721   return round...

Python request to picoW

Image
 Python request to picoW Sending clicks to picow working via Chrome browser and HTML. Want to strip back all that and get just simple python requests to work in an ap network with Picos. Screen shot shows header (HTTP /1.1 ....) on html that python on the pc can respond to. Without that it rejects pico's response. See below: Here's the html : HTTP/1.1 200 OK Content-Type: text/csv <!DOCTYPE html> <html> <head>     <title>Raspberry Pi Pico Simple LED</title> </head> <body> <p>Click the buttons to control the LED</p> <input type="button" onclick="document.location='/ledon'" value="TURN LED ON"/> <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...

Internal temperature and buttons working

Image
  Added temperature code from temperature0.py to old WiFiAPLEDS3.py. to give new WiFiSensor0.py                                                                                                                                               

Led on and off via AP network. First go.

Image
 Took some code from elsewhere. Got to control leds on PicoW via buttons on Chrome. See below: The Thonny micropython program WiFiAPLEDS1.py is here  <script src="https://pastebin.com/embed_js/APvZscup"></script> and  was based on a previous one, WiFiAP0.py and also used for finding a key word like 'ledon' in response this site . The internet access had to be set to internal AL network called NAME and away from Spark's usual one. The simpleled.html file follows:(some parts not used) <!DOCTYPE html> <html> <head>     <title>Raspberry Pi Pico Simple LED</title> </head> <body> <p>Click the buttons to control the LED</p> <input type="button" onclick="document.location='/ledon'" value="TURN LED ONnnnn"/> <p></p> <input type="button" onclick="document.location='/ledoff'" value="TURN LED OFF"/> <p><...

PICO AP network sends csv log file to python script and browser

Image
 Having issues with local AP network names and passwords. Old attempts seem to stay sticky. Have unplugged pico, issued new ssid, password pair, see below and this seems to clear the decks and give me the csv file, made up in Notepad, back to PC via browser, which prompts for where to put this file or to python network request script that just spits it out on the screen.  Pastebin of micropython below <script> Got most of the code from Perplexity ai. .  <script src="https://pastebin.com/embed_js/Aqt5QPVD"></script>

Pi Pico AP network with Python

 Perplexity, AI app, created the following program: ---------------------------------------------- import network import socket # Set up access point ap = network.WLAN(network.AP_IF) ap.active(True) ap.config(essid='PicoW_AP') # Wait for connection while not ap.isconnected():     pass print('AP Mode Is Active, You can Now Connect') print('IP Address To Connect to::', ap.ifconfig()[0]) # Set up socket addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1] s = socket.socket() s.bind(addr) s.listen(1) print('Listening on', addr) while True:     cl, addr = s.accept()     print('Got a connection from', addr)     request = cl.recv(1024)     print('Content received by Pico =', request)     # Send a proper HTTP response     response = """\ HTTP/1.1 200 OK Content-Type: text/html Content-Length: 44 <html><body><h1>Hello, World!</h1></body></html> """     cl.send(response)   ...

Requests via uPy "requests" library

Image
 Installed request library into Python310 via : C:\Users\Dell\AppData\Local\Programs\Python\Python310\Scripts where pip lives.  Then did a pip install requests to get the library put into scripts folder. Can see it's there with  pip install list -v . Wrote this simple request program based on W3 Schools' one: -------------------------------------- import requests #the required first parameter of the 'get' method is the 'url':  x = requests.get('https://w3schools.com/python/demopage.htm') #x=requests.get('https://google.com') #print the response text (the content of the requested file): print(x.text) -----------------------------------------------------and got back -------- = RESTART: C:\Users\Dell\AppData\Local\Programs\Python\Python310\myfiles\request0.py <!DOCTYPE html> <html> <body> <h1>This is a Test Page</h1> </body> </html> --------------------------------------Had to use 'normal internet' ...

Micropython requests via Thonny

Image
 Pi Pico sets up local AP network and sends some led buttons yo browser request on 192.168.4.1 Then clicking the buttons causes Pico to receive extra information of URL like /ledon and /ledoff so that the pico can interrogate this response code and change leds or do anything else. Would really like this to initiate an sending of a data-logging file in text that sends lots of sensor data back to browser to be handled by other software like Excel. #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 file = open("simpleled.html") html = file.read() file.close() def web_page():   html = """<html><head><meta name="viewport" content="width=device-width, initial-scale=1"></head>             <body><h1>Hello 33v21World</h1></body></html>          """   return html #todo make this ...

Pico W and time server. Worked.

Image
 Pico W queries time server.https://www.timeapi.io/api/Time/current/zone?timeZone=Pacific/Auckland # use web service to get date and time information  Worked for google Sun Aug  4 12:26:29 NZST 2024 #Also worked for time server Sun Aug  4 12:26:29 NZST 2024  import utime import network import urequests #from NetworkCredentials import NetworkCredentials import NetworkCredentials ssid = NetworkCredentials.ssid password = NetworkCredentials.password # set WiFi to station interface wlan = network.WLAN(network.STA_IF) # activate the network interface wlan.active(True) # connect to wifi network wlan.connect(ssid, password) max_wait = 10 # wait for connection while max_wait > 0:     """         0   STAT_IDLE -- no connection and no activity,         1   STAT_CONNECTING -- connecting in progress,         -3  STAT_WRONG_PASSWORD -- failed due to incorrect password,   ...

Pi PicoW and WiFi0

Image
 Got PicoW to send HTML Hello World web page to chrome browser via internet. The program from Creating a Wireless Network With Raspberry Pi Pico W Part 1 - Instructables below created an access point in a PicoW ie. put it into AP mode. Pics: Code in black bit lower import network import time import socket def web_page(): html = """<html><head><meta name="viewport" content="width=device-width, initial-scale=1"></head> <body><h1>Hello World</h1></body></html> """ return html # 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...