Ben Boardwalk Project finished phase1

THis started to fail when new if--elif options added. REcast as simpler version. Don't use this version. Use next one called minresponse3.py. See above...


 Ben Boardwalk Project more or less finished phase1. This is temperature and logging data is captured by PC HTML client form from Pi PicoW web server that's doing the logging and the sensing. Early days but structures seem fine and micropython code is relatively organised.

Here is pic of a client session. Just asked for logging data which goes into file dialog query.



The main file is the micropython file bensense12.py. It establishes the AP network, called NAME and awaits query from chrome html form called bensensor5.html. Mostly buttons that cause a cascade of if,elif statements to sort through all the options and return with information that gets printed on the form, like temperature or, new work for me, gets the browser to save a log file, not print it, to via a normal Windows dialog. 

Here's the main program written in micropython using Thonny:

#Worked ok Tue Aug  6 11:04:01 NZST 2024. Can't get other mode to work  Will play with this one.
#Sun Sep  1 11:46:42 NZST 2024. Going to write route finder for all the paths from HTML form
#Mon Sep  2 12:20:06 NZST 2024. Tidied up all loose comments. Now ready for sensors.
#trying tidyup Tue Sep 10 11:06:12 NZST 2024
#Wed Sep 11 11:30:24 NZST 2024. INternal temp seems to be working with html form. ext temp stub done.
import network
import time
import socket
from machine import Pin
import parse_request1   #added this, based on perplexity
import parreqlite1
import do_ledon, do_ledoff, do_inttemp,do_exttemp, do_text, do_csv,do_other
led = machine.Pin("LED", machine.Pin.OUT)
led.on()
# adcpin = 4
# sensor = machine.ADC(adcpin)    #for internal temp
# ts=type(sensor)
# print(ts)
def ap_mode(ssid, password):
    file = open("bensensor5.html")  #initialize html
    html2 = file.read()
    file.close()
    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.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)   #promising fix?
    s.bind(('', 80))
    s.listen(5)
    
    while True:
      conn, addr = s.accept()
      print('Got a connection from %s' % str(addr))
      request = conn.recv(1024)
      
      if len(request) > 1:    #0: 
          meth,pa,prot=parreqlite1.parse_request1(request)
          print("Pa0 =....",pa)
          #print("Path0 =....",path)
          path = pa # 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
                #x=query_params["sensor"]
                #print("queryp isss..and path is, and query_params[sensor]",query_params, path,x)      
          print("Path =....",path)
          print (query_params)
          
          if path == '/ledon':   #new
              x,st=do_ledon.do_ledon()
              led.value(1)
              html2=st
          elif path ==('/ledoff'):
              x,st=do_ledoff.do_ledoff()
              led.value(0)
              html2=st
          elif path == '/sensors':
              k=query_params['sensor']
              print ("k for query_params is  ...",k)
              if k == "External+temperature":
                  print("Got external temp ,...")
                  st = do_exttemp.do_exttemp()
                  html2 = st
                  
              elif k == "Internal+temperature":
                  print("Got internal  temp xxxxx ,...")
                  st = do_inttemp.do_inttemp()
                  html2 = st
              elif k == "SENSOR1":
                  print("Got sensor1  value ,...")
                  
          elif path == '/files':
              k=query_params["file"]
              if k== "log":
                  print("Got log...")
                  st = do_text.do_text()
                  html2 =st
              elif k== "csv":
                  print("Got csv..." )
                  st = do_csv.do_csv()
                  html2 = st
              elif k== "other":
                  print("Got other file..." )
                  st=do_other.do_other()
                  html2 =st
                  
          else:
              print("Query problem..., path, len(request)", path, len(request))
      
      
      response=html2 #new
      conn.send(response)
      conn.close()
      
ap_mode('NAME',
        'PASSWORD')
#todo put -->html = html.replace('**ledState**', led_state_text) before line 79

-------------------------------------------------------------------------below is html file---------
=====bensonsor5.html ==================
<!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="sensors">
      <p>Please select your favorite Web language:</p>
        <input type="radio" id="sensor1" name="sensor" value="SENSOR1">
        <label for="html">Sensor1</label><br>
        <input type="radio" id="exttemp" name="sensor" value="External temperature" checked >
        <label for="css">Ext temp</label><br>
        <input type="radio" id="inttemp" name="sensor" value="Internal temperature">
        <label for="javascript">Int temp</label>
        <input type="submit" value="Submit">
           
    </form>
  <br> 
    <form action="files">
      <p>Please select file type:</p>
      <input type="radio" id="fil1" name="file" value="csv">
      <label for="fil1">csv file</label><br>
      <input type="radio" id="fil2" name="file" value="log">
      <label for="fil2">log file</label><br>
      <input type="radio" id="fil3" name="file" value="other" checked>
      <label for="fil3">other type</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>
===========================
------here, below is typical sensor subroutine-----------do_inttemp.py
#do_inttemp
import machine
adcpin = 4
sensor = machine.ADC(adcpin)
def do_inttemp():
    adc_value = sensor.read_u16()
    volt = (3.3/65535) * adc_value
    temperature = 27 - (volt - 0.706)/0.001721

    file = open("bensensor5.html")
    html = file.read()
    file.close()
    html3 = html.replace('**TEMP**',str(round(temperature,1)))
    return html3
  
=============below is function that gets csv file for saving-------
#do_text.py

def do_csv():
    # Attempt to read the my-log.txt file
    try:
        with open('log.csv', 'r') as file:  #('simpleled2.html', 'r')
            log_data = file.read()
    except OSError:
        log_data = "Error: my-log.txt file not found."
        
    html3 = """\
HTTP/1.1 200 OK
Content-Type: text/csv
Content-Disposition: attachment; filename="log.csv"
Content-Length: {}

{}

""".format(len(log_data), log_data)  #(len(x), x)

    
   
    return html3
  
================
To do: Save all the relevat files in pastebin. Done
Next check that the iPhone can run all this in a little chrome browser.
Tidy up code and all the do_xx routines. Some left=over comments etc
Work out why led changes don't work on iPhone but rest pretty good.

Phase 2 would include some of this:
detach picoW and run off batteries at short distance.
Take this into ben enviornemnt and test with iPhone.
Add in breadboard version with oled and DSxx 1-wire temperature sensor.
Create scematic voa EasyEDA then make board for full version.

Handyscan:
MicroPython v1.23.0 on 2024-06-02; Raspberry Pi Pico W with RP2040

Type "help()" for more information.

>>> import network
>>> wlan = network.WLAN(network.STA_IF)
>>> wlan.active(True)
>>> print(wlan.scan())
[(b'SPARK-DTCUB2', b'\x14\xa5\x1a\x08\xf9\xc8', 5, -61, 7, 6)]
>>> 

Comments

Popular posts from this blog

Reading LittleFS file into buffer for sending

ESP32 buttons and bouncing