0

I am running a script of led turn on and off on my esp32 device from a web page. Like this:

import machine
led = machine.Pin(2,machine.Pin.OUT)
led.off()


import network

sta = network.WLAN(network.STA_IF)
if not sta.isconnected():
    print('connecting to network...')
    sta.active(True)
    #sta.connect('your wifi ssid', 'your wifi password')
    sta.connect("Dream Net R-632", "07132711")
    while not sta.isconnected():
        pass
esp_ip = sta.ifconfig()[0]
print('IP :', esp_ip)


import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('',80))
s.listen(5)     # max of 5 socket connections

def web_page():
    if led.value()==1:
        led_state = 'ON'
        print('led is ON')
    elif led.value()==0:
        led_state = 'OFF'
        print('led is OFF')

    html_page = """   
      <html>   
      <head>   
       <meta content="width=device-width, initial-scale=1" name="viewport"></meta>   
      </head>   
      <body>   
        <center><h2>ESP32 Web Server in MicroPython </h2></center>   
        <center>   
         <form>   
          <button name="LED" type="submit" value="1"> LED ON </button>   
          <button name="LED" type="submit" value="0"> LED OFF </button>   
         </form>   
        </center>   
        <center><p>LED is now <strong>""" + led_state + """</strong>.</p></center>   
      </body>   
      </html>"""  
    return html_page   

while True:
    client_socket, client_address = s.accept()
    print("Got connection from %s" % str(client_address))

    request = client_socket.recv(1024)
    print("")
    request_str = request.decode('utf-8')
    print("Content:", request_str)

    request = str(request)
    led_on = request.find('/?LED=1')
    led_off = request.find('/?LED=0')
    if led_on == 6:  #Better to use != -1 as a response to find failed
        print('LED ON')
        print(str(led_on))
        led.value(1)
    elif led_off == 6:
        print('LED OFF')
        print(str(led_off))
        led.value(0)
    response = web_page()
    client_socket.send('HTTP/1.1 200 OK\n')
    client_socket.send('Content-Type: text/html\n')
    client_socket.send('Connection: close\n\n')
    client_socket.sendall(response)
    client_socket.close()

In this script iam writing the .html code within the python script(which will not be compatible if i have to write large scripts of HTML and will make the code messy). I want it to be written seperately and just called where needed.

I had tried doing the following stuff:

file = open("webled.html")
    html = file.read()
    file.close()

    html = html.replace('**ledState**', led_state)
    client.send(html)
    client.close()

Didn't worked. So i tried the following:

    with open('webled.html', 'r') as file:
        response += file.read()
    html = html.replace('**ledState**', led_state)
    conn.send(response)
    conn.close()

Also by mentioning complete directory as:

with open('/Users/MJ/Desktop/M-Python/New folder/webled.html', 'r') as file:
        response += file.read()
    conn.send(response)
    conn.close()

None of them worked and returning error messsage as: *Traceback (most recent call last): File "", line 105, in OSError: [Errno 2] ENOENT


  • YES MY PYTHON CODE AND webled.html ARE IN THE SAME DIRECTORY-

My html file is named as webled.html and it contains:

<html>    
    <head>    
     <meta content="width=device-width, initial-scale=1" name="viewport"></meta>    
    </head>    
    <body>    
     <center><h2>ESP32 Web Server in MicroPython </h2></center>    
     <center>    
      <form>    
      <button name="LED" type="submit" value="1"> LED ON </button>    
      <button name="LED" type="submit" value="0"> LED OFF </button>  
      </form>    
     </center>    
     <center><p>The LED is **ledState**</p></strong>.</p></center>    
    </body>    
    </html>
1
  • 1
    The absolute path probably refers to your PC but not to the file system on the ESP32 (but it should). Commented Apr 12, 2023 at 12:08

1 Answer 1

3

You're headed in the right direction. Something like this is absolutely the way to do it (you probably don't want to open and read the file for every request, but the principle is sound):

with open("webled.html") as fd:
    html = fd.read()
    html = html.replace('**ledState**', led_state)
    client.send(html)
    client.close()

Of course, for this to work you need to create the file webled.html on your esp32. How are you getting your Python code to the esp32? You should be able to use the same process for transferring the HTML file.


I've modified your code so that it looks like the following. Note that I've made a few simplifications here and there:

import network
import socket
import machine


led = machine.Pin(2, machine.Pin.OUT)
led.off()

with open("webled.html") as fd:
    html_template = fd.read()


def connect():
    sta = network.WLAN(network.STA_IF)
    if not sta.isconnected():
        print("connecting to network...")
        sta.active(True)
        # sta.connect('your wifi ssid', 'your wifi password')
        sta.connect("vks-1", "1small1wide1long")
        while not sta.isconnected():
            pass
    esp_ip = sta.ifconfig()[0]
    print("IP :", esp_ip)


def web_page():
    if led.value() == 1:
        led_state = "ON"
    elif led.value() == 0:
        led_state = "OFF"

    return html_template.replace("**ledState**", led_state)


def main():
    connect()

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(("", 80))
    s.listen(5)  # max of 5 socket connections

    while True:
        client_socket, client_address = s.accept()
        print("Got connection from %s" % str(client_address))

        request = client_socket.recv(1024)
        print("")
        request_str = request.decode("utf-8")
        print("Content:", request_str)

        if b"/?LED=1" in request:
            print("LED ON")
            led.value(1)
        elif b"?LED=0" in request:
            print("LED OFF")
            led.value(0)

        response = web_page()
        client_socket.send("HTTP/1.1 200 OK\n")
        client_socket.send("Content-Type: text/html\n")
        client_socket.send("Connection: close\n\n")
        client_socket.sendall(response)
        client_socket.close()


main()

And I have the following content in webled.html:

<html>
  <head>
    <meta content="width=device-width, initial-scale=1" name="viewport"></meta>
  </head>
  <body>
    <center><h2>ESP32 Web Server in MicroPython </h2>
      <form>
        <button name="LED" type="submit" value="1"> LED ON </button>
        <button name="LED" type="submit" value="0"> LED OFF </button>
      </form>
      <p>LED is now <strong>**ledState**</strong>.</p>
    </center>
  </body>
</html>

I use ampy to transfer files to my esp device. The process looks like this:

ampy -p /dev/ttyUSB1 put main.py
ampy -p /dev/ttyUSB1 put webled.html

After transferring these files, I can access the web page and control the LED using the "LED ON" and "LED OFF" buttons

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, got it! So, the reason why the error was popping up was that I was being a total noob and just running the Python script straight from the IDE, without uploading the .HTML file giving it a chance to get there. Thanks for the heads up!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.