Skip to content

Commit 15eefba

Browse files
committedNov 25, 2022
MicroPython Web Server using MicroDot initial code
1 parent 80c4084 commit 15eefba

11 files changed

+1890
-0
lines changed
 

‎boot.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# boot.py -- run on boot-up
2+
import network, utime
3+
4+
# Replace the following with your WIFI Credentials
5+
SSID = "<PLACE_YOUR_SSID_HERE>"
6+
SSI_PASSWORD = "<PLACE_YOUR_WIFI_PASWORD_HERE>"
7+
8+
def do_connect():
9+
import network
10+
sta_if = network.WLAN(network.STA_IF)
11+
if not sta_if.isconnected():
12+
print('connecting to network...')
13+
sta_if.active(True)
14+
sta_if.connect(SSID, SSI_PASSWORD)
15+
while not sta_if.isconnected():
16+
pass
17+
print('Connected! Network config:', sta_if.ifconfig())
18+
19+
print("Connecting to your wifi...")
20+
do_connect()
21+

‎connect_wifi.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import network, utime
2+
3+
import esp
4+
esp.osdebug(None)
5+
6+
import gc
7+
gc.collect()
8+
9+
# def do_connect():
10+
# try:
11+
# sta_if = network.WLAN(network.STA_IF)
12+
# if not sta_if.isconnected():
13+
# sta_if.active(True)
14+
# sta_if.connect('donsky-4thFloor', 'donsky982')
15+
# while not sta_if.isconnected():
16+
# pass
17+
# print('network config:', sta_if.ifconfig())
18+
# except Exception as e:
19+
# print("Error encountered", e)
20+
#
21+
#
22+
#
23+
# do_connect()
24+
print("Starting station connection...")
25+
station = network.WLAN(network.STA_IF)
26+
print("After define...")
27+
station.active(True)
28+
print("Start connecting...")
29+
try:
30+
station.connect("donsky-4thFloor", "donsky982")
31+
print("Establishing connection...")
32+
for i in range(10):
33+
print("Connecting to station in {}".format(i))
34+
utime.sleep(1)
35+
if station.isconnected():
36+
break
37+
38+
if station.isconnected():
39+
print("station Connection OK!")
40+
print("Network Config ", station.ifconfig())
41+
else:
42+
print("station internal error")
43+
except Exception as e:
44+
print(e)

‎led_module.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from machine import Pin
2+
3+
class LEDModule:
4+
"""This will represent our LED"""
5+
6+
def __init__(self, pinNumber):
7+
self.pinNumber = pinNumber
8+
self.led_pin = Pin(self.pinNumber, Pin.OUT)
9+
10+
def get_value(self):
11+
return self.led_pin.value()
12+
13+
def toggle(self):
14+
self.led_pin.value(not self.get_value())
15+
16+

‎main.py

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
from microdot_asyncio import Microdot, Response, send_file
2+
from microdot_utemplate import render_template
3+
from led_module import LEDModule
4+
5+
app = Microdot()
6+
Response.default_content_type = 'text/html'
7+
8+
# Our LED Module
9+
led_module = LEDModule(23)
10+
11+
12+
@app.route('/')
13+
async def index(request):
14+
return render_template('index.html', led_value=led_module.get_value())
15+
16+
17+
@app.route('/toggle')
18+
async def toggle_led(request):
19+
print("Receive Toggle Request!")
20+
led_module.toggle()
21+
return "OK"
22+
23+
24+
@app.route('/shutdown')
25+
async def shutdown(request):
26+
request.app.shutdown()
27+
return 'The server is shutting down...'
28+
29+
30+
@app.route('/static/<path:path>')
31+
def static(request, path):
32+
if '..' in path:
33+
# directory traversal is not allowed
34+
return 'Not found', 404
35+
return send_file('static/' + path)
36+
37+
app.run()

‎microdot.py

+1,175
Large diffs are not rendered by default.

‎microdot_asyncio.py

+439
Large diffs are not rendered by default.

‎microdot_utemplate.py

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
from utemplate import recompile
2+
3+
_loader = None
4+
5+
6+
def init_templates(template_dir='templates', loader_class=recompile.Loader):
7+
"""Initialize the templating subsystem.
8+
9+
:param template_dir: the directory where templates are stored. This
10+
argument is optional. The default is to load templates
11+
from a *templates* subdirectory.
12+
:param loader_class: the ``utemplate.Loader`` class to use when loading
13+
templates. This argument is optional. The default is
14+
the ``recompile.Loader`` class, which automatically
15+
recompiles templates when they change.
16+
"""
17+
global _loader
18+
_loader = loader_class(None, template_dir)
19+
20+
21+
def render_template(template, *args, **kwargs):
22+
"""Render a template.
23+
24+
:param template: The filename of the template to render, relative to the
25+
configured template directory.
26+
:param args: Positional arguments to be passed to the render engine.
27+
:param kwargs: Keyword arguments to be passed to the render engine.
28+
29+
The return value is an iterator that returns sections of rendered template.
30+
"""
31+
if _loader is None: # pragma: no cover
32+
init_templates()
33+
render = _loader.load(template)
34+
return render(*args, **kwargs)

‎static/css/entireframework.min.css

+1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎static/css/index.css

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/******** mincss **********/
2+
.hero {
3+
background: #eee;
4+
padding: 20px;
5+
border-radius: 10px;
6+
margin-top: 1em;
7+
text-align: center;
8+
9+
}
10+
11+
.hero h1 {
12+
margin-top: 0;
13+
margin-bottom: 0.3em;
14+
color: red;
15+
}
16+
17+
/****** Custom toggle Switch**********/
18+
/* https://codepen.io/alvarotrigo/pen/abVPyaJ */
19+
/*********************/
20+
.toggle-div{
21+
display: flex;
22+
justify-content: center;
23+
align-items: center;
24+
margin-top: 5em;
25+
}
26+
27+
.label{
28+
font-size: 1.5em;
29+
font-weight: bolder;
30+
margin-right: 0.5em;
31+
/* color: blue */
32+
}
33+
34+
/* Styles for the toggle switch */
35+
input[type=checkbox] {
36+
height: 0;
37+
width: 0;
38+
visibility: hidden;
39+
}
40+
41+
label {
42+
cursor: pointer;
43+
text-indent: -9999px;
44+
width: 150px;
45+
height: 60px;
46+
background: grey;
47+
display: block;
48+
border-radius: 100px;
49+
position: relative;
50+
}
51+
52+
label:after {
53+
content: "";
54+
position: absolute;
55+
top: 5px;
56+
left: 5px;
57+
width: 70px;
58+
height: 50px;
59+
background: #fff;
60+
border-radius: 90px;
61+
transition: 0.3s;
62+
}
63+
64+
input:checked + label {
65+
background: #bada55;
66+
}
67+
68+
input:checked + label:after {
69+
left: calc(100% - 5px);
70+
transform: translateX(-100%);
71+
}
72+
73+
label:active:after {
74+
width: 130px;
75+
}

‎static/js/index.js

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
function toggleButtonSwitch(e) {
2+
var switchButton = document.getElementById("switch");
3+
4+
var toggleValue = "";
5+
if (switchButton.checked) {
6+
console.log("On!");
7+
toggleValue = "ON";
8+
} else {
9+
console.log("Off!");
10+
toggleValue = "OFF"
11+
}
12+
fetch( `/toggle`)
13+
.then( response => {
14+
console.log(response);
15+
} )
16+
}

‎templates/index.html

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
{% args led_value %}
2+
<!DOCTYPE html>
3+
<html>
4+
<head>
5+
<meta charset="UTF-8" />
6+
<meta name="viewport" content="width=device-width, initial-scale=1" />
7+
<title>MicroPython Webserver</title>
8+
<link rel="stylesheet" href="static/css/entireframework.min.css" />
9+
<link rel="stylesheet" href="static/css/index.css" />
10+
<script src="static/js/index.js"></script>
11+
</head>
12+
<body>
13+
<nav class="nav" tabindex="-1" onclick="this.focus()">
14+
<div class="container">
15+
<a class="pagename current" href="#">www.donskytech.com</a>
16+
<a href="#">One</a>
17+
<a href="#">Two</a>
18+
<a href="#">Three</a>
19+
</div>
20+
</nav>
21+
<button class="btn-close btn btn-sm">×</button>
22+
<div class="container">
23+
<div class="hero">
24+
<h1 class="title">MicroPython Webserver</h1>
25+
<div class="toggle-div">
26+
<p class="label">Toggle Switch</p>
27+
<input type="checkbox" id="switch" onclick="toggleButtonSwitch()" {% if led_value == 1 %} checked {% endif %}/><label for="switch">Toggle</label>
28+
</div>
29+
</div>
30+
</div>
31+
</body>
32+
</html>

0 commit comments

Comments
 (0)
Please sign in to comment.