Webserver

Download all scripts: 8-webserver.zip

8-webserver_onboard_led_on_off.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Import required items from the built in library
import RPi.GPIO as GPIO  # Used to control the GPIO pins ('general purpose input/output')
import socket  # Provide a low-level networking interface

# Setup the GPIO channels
GPIO.setmode(GPIO.BCM)  # Set the pin numbering mode [^1]
led = 47  # The GPIO pin the green 'ACT' onboard LED is connected to.
GPIO.setup(led, GPIO.OUT)  # Set the GPIO channel up to be used as output.

# HTML response (the curly brackets in the CSS part have to be escaped)
http_header = """HTTP/1.0 200 OK
Content-Type: text/html

"""
html = """<!DOCTYPE html>
<html>
	<head>
		<title>Raspberry Pi Python onboard LED on/off</title>
		<style>
			body {{
				font-family: Arial, Helvetica, sans-serif;
				font-size: 2em;
				font-weight: bold;
				text-align: center; }}
			button {{
				border: 0;
				background: #cccccc;
				box-shadow: none;
				width: 6em;
				line-height: 4em;
				border-radius: .5em;
				font-size: inherit;  
				font-weight: bold; }}
			form {{
				font-size: 1.5em;
			}}
			.active.on {{
				background: #33cc33; }}
			.active.off {{
				background: #cc3333; }}
		</style>
	</head>
	<body>
		<h1>Python Webserver</h1>
		<form>
			Turn onboard LED<br/>
			<br/>
			<button name="led" value="on" type="submit" class="on {button_on}">On</button>
			<button name="led" value="off" type="submit" class="off {button_off}">Off</button>
		</form>
	</body>
</html>
"""

# Setup a TCP socket to listen for incoming connections
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_socket.bind(('', 1024))  # 
tcp_socket.listen(5)  # 5 = backlog argument: the number of unaccepted connections

while True:
	connnection, address = tcp_socket.accept()
	print('Connection from {}'.format(address))
	request = connnection.recv(1024)  # Read http header
	request = request.decode('utf-8')  # Convert binary string to UTF-8
	request = request.split('\n')[0]  # Get first line, e.g. 'GET /?led=on HTTP/1.1'
	request = request.split()[1]  # Get second item, e.g. '/?led=on'
	request = request[1:]  # Remove '/?' from the beginning
	
	if '=' in request:
		request = request.split('=')[1]
	else:
		request = 'off'
	
	print('Turn LED {}'.format(request))
	
	if request == 'on':
		GPIO.output(led, GPIO.HIGH)
		button_states = {'button_on': 'active', 'button_off': ''}
	else:
		GPIO.output(led, GPIO.LOW)
		button_states = {'button_on': '', 'button_off': 'active'}
	
	response = http_header + html.format(**button_states)
	response = response.encode('utf-8')

	connnection.send(response)
	connnection.close()