Web Server Control Lab

Task 4

Task 4 - Custom Text to LCD (15 pts)

• Add a textbox and a Send button to the web page.

• Text entered by the user must appear on the LCD.

• Text longer than 16 characters should scroll across the LCD.

• Evidence: Short video showing text sent from the browser to the LCD

The webpage should display similar to this 

Task 4

Import the library

import network
import socket
import time

from machine import Pin, SoftI2C
from machine_i2c_lcd import I2cLcd

Wifi Setting

# WIFI SETTINGS

ssid = "---"
password = "---"

Servo Setup

# LCD SETUP

I2C_ADDR = ________ ## Add the LCD Address

i2c = SoftI2C(
    sda=Pin(21),
    scl=Pin(22),
    freq=400000
)

lcd = I2cLcd(
    i2c,
    I2C_ADDR,
    2,
    16
)

lcd.clear()
### Display the "IoT LAB" on the first row
________

### Display the "Task 2" on the second row
________

time.sleep(2)

lcd.clear()

Task 4

DECODE TEXT FROM URL Function 

### DECODE TEXT FROM URL



def url_decode(text):

    result = bytearray()
    index = 0

    while index < len(text):

        if text[index] == "+":

            # Convert + to a space
            result.append(32)
            index += 1

        elif text[index] == "%":

            try:
                hex_value = text[
                    index + 1:index + 3
                ]

                result.append(
                    int(hex_value, 16)
                )

                index += 3

            except:
                index += 1

        else:

            result.extend(
                text[index].encode()
            )

            index += 1

    try:
        return result.decode("utf-8")

    except:
        return str(result)

Task 4

Display the text on the LCD

def display_message(message):
	lcd.clear()
	### write a code in here to diplay the message on the LCD with lcd.putstr() if the lenght of the message is less than 16. 
    ### If the message is more than 16, use lcd.scroll_text() to display the message
    ________

Task 4

Webpage Function

# CREATE WEBPAGE

def create_webpage():

    html = """
<!DOCTYPE html>

<html>

<head>

    <title>ESP32 LCD Control</title>

    <meta name="viewport"
          content="width=device-width,
                   initial-scale=1">

    <style>

        body {
            font-family: Arial;
            text-align: center;
            background-color: ________;
            padding: 20px;
        }

        h1 {
            color: ________;
        }

        .card {
            background-color: white;
            width: ________;
            margin: ________ ________;
            padding: ________;
            border-radius: ________;

            box-shadow:
                0 2px 8px
                rgba(0, 0, 0, 0.2);
        }

        input[type="text"] {
            width: 260px;
            padding: 12px;
            font-size: 16px;
            border: 1px solid #cccccc;
            border-radius: 6px;
            margin-bottom: 15px;
        }

        button {
            background-color: #0066cc;
            border: none;
            color: white;
            padding: ________ ________;
            border-radius: ________;
            font-size: 16px;
            cursor: pointer;
        }

        button:hover {
            background-color: ________;
        }

        #status {
            color: #28a745;
            margin-top: 15px;
            font-weight: bold;
        }

    </style>

    <script>

        function sendMessage() {

            var message =
                document.getElementById(
                    "message"
                ).value;

            if (message == "") {

                document.getElementById(
                    "status"
                ).innerHTML =
                    "Please enter a message.";

                return;
            }

            fetch(
                "/message?text=" +
                encodeURIComponent(message)
            );

            document.getElementById(
                "status"
            ).innerHTML =
                "Message sent to LCD";
        }

    </script>

</head>

<body>

    <h1>________</h1>

    <div  ### Add class card with the input to insert the message
    	________

        <br>

        <button onclick="sendMessage()">
            Send
        </button>

        <p id="status"></p>

    </div>

</body>

</html>
"""

    return html

Task 4

WIFI Connection 


wifi = network.WLAN(
    network.STA_IF
)

wifi.active(True)

if not wifi.isconnected():

    print("Connecting to Wi-Fi...")

    wifi.connect(
        ssid,
        password
    )

    while not wifi.isconnected():

        print(".", end="")
        time.sleep(1)


ip = wifi.ifconfig()[0]

print()
print("Wi-Fi connected!")
print("ESP32 IP address:", ip)
print("Open this address:")
print("http://" + ip)


# ==============================
# START WEB SERVER
# ==============================

address = socket.getaddrinfo(
    "0.0.0.0",
    80
)[0][-1]

server = socket.socket()

server.setsockopt(
    socket.SOL_SOCKET,
    socket.SO_REUSEADDR,
    1
)

server.bind(address)
server.listen(1)

print("Web server is running...")

Task 4

Main Program

# MAIN PROGRAM
while True:

    client = None

    try:
        client, client_address = (
            server.accept()
        )

        request = client.recv(1024)
        request = request.decode()

        request_line = request.split(
            "\r\n"
        )[0]

        print("Request:", request_line)


      
        # RECEIVE CUSTOM TEXT
     

        if "GET /message?text=" in request_line:

            start = ________

            end = ________

            encoded_message =________

            message = ________

            print("Message:", message)

            # Respond before scrolling
            client.send(
                "HTTP/1.1 204 No Content\r\n"
            )

            client.send(
                "Connection: close\r\n"
            )

            client.send("\r\n")

            client.close()
            client = None

            # Display or scroll the message
            ________


    
        # SEND WEBPAGE
    

        else:

            webpage = create_webpage()

            client.send(
                "HTTP/1.1 200 OK\r\n"
            )

            client.send(
                "Content-Type: text/html\r\n"
            )

            client.send(
                "Connection: close\r\n"
            )

            client.send("\r\n")

            client.sendall(webpage)


    except Exception as error:

        print(
            "Server error:",
            error
        )


    finally:

        if client is not None:
            client.close()