WEB Server
-
Any good news about having a web server?
-
@constantinos
What do you mean? -
OK. Your are right. I have to be more specific.
In ESP8266 Arduino Core a httpserver class exists. It is very easy to setup a web server. I was wondering if exists something similar for pyCom. -
I don't think that there's something builtin like Python's
SimpleHTTPServerbut the following topics might help you:https://github.com/RinusW/WiPy/tree/master/AiCWebserver
http://forum.micropython.org/viewtopic.php?t=1033 -
also this can be somehow helpfull(it is normal python but..) if you need extend functionality
https://hg.python.org/cpython/file/3.6/Lib/http/server.py -
Hi,
If you are interested in a web server and a template language (.pyhtml) for pycom modules in micropython, you can try this release :
https://github.com/jczic/MicroWebSrv(Be careful though, this takes memory.)
-
@jczic I am trying hard to make working MicroWebServer. In fact IsStarted return me always false. I really have no idea what I have to do.
I tried different solution but without succes. WOuld it be possible to tell what wrong I did? Did I missed apackage?I supposed, I should connect the the WLAN 'lypo4_1' and open a browser with the 192.168.0.1?
My structure is
myProject/flash/www
myProject/js
myProject/main.py
myProject/boot.py
myProject/microWebSocket.py
myProject/microWebSrv.py
myProject/microWebTemplate.pyHere is my code
#import socket
#import time
#import binascii
import pycomfrom network import WLAN
#from pysense import Pysense
from microWebSrv import MicroWebSrv#py = Pysense()
print('\n\n** Init WLAN mode and WAP2')
wlan = WLAN(mode=WLAN.AP,ssid="lypo4_1",auth=(WLAN.WPA2,'00000000')) # we call the constructor without params
print('\n\n** Next...')----------------------------------------------------------------------------
def _httpHandlerTestGet(httpClient, httpResponse) :
content = """
<!DOCTYPE html>
<html lang=fr>
<head>
<meta charset="UTF-8" />
<title>TEST GET</title>
</head>
<body>
<h1>TEST GET</h1>
Client IP address = %s
<br />
<form action="/test" method="post" accept-charset="ISO-8859-1">
First name: <input type="text" name="firstname"><br />
Last name: <input type="text" name="lastname"><br />
<input type="submit" value="Submit">
</form>
</body>
</html>
""" % httpClient.GetIPAddr()
httpResponse.WriteResponseOk( headers = None,
contentType = "text/html",
contentCharset = "UTF-8",
content = content )def _httpHandlerTestPost(httpClient, httpResponse) :
formData = httpClient.ReadRequestPostedFormData()
firstname = formData["firstname"]
lastname = formData["lastname"]
content = """
<!DOCTYPE html>
<html lang=fr>
<head>
<meta charset="UTF-8" />
<title>TEST POST</title>
</head>
<body>
<h1>TEST POST</h1>
Firstname = %s<br />
Lastname = %s<br />
</body>
</html>
""" % ( MicroWebSrv.HTMLEscape(firstname),
MicroWebSrv.HTMLEscape(lastname) )
httpResponse.WriteResponseOk( headers = None,
contentType = "text/html",
contentCharset = "UTF-8",
content = content )def _acceptWebSocketCallback(webSocket, httpClient) :
print("WS ACCEPT")
webSocket.RecvTextCallback = _recvTextCallback
webSocket.RecvBinaryCallback = _recvBinaryCallback
webSocket.ClosedCallback = _closedCallbackdef _recvTextCallback(webSocket, msg) :
print("WS RECV TEXT : %s" % msg)
webSocket.SendText("Reply for %s" % msg)def _recvBinaryCallback(webSocket, data) :
print("WS RECV DATA : %s" % data)def _closedCallback(webSocket) :
print("WS CLOSED")print('\n\n** routeHandle')
routeHandlers = [
( "/test", "GET", _httpHandlerTestGet ),
( "/test", "POST", _httpHandlerTestPost )
]
print('\n\n** MicroWebserv')
#srv = MicroWebSrv(routeHandlers=routeHandlers)
#srv = MicroWebSrv(routeHandlers=None, port=80, webPath="/flash/www")
srv = MicroWebSrv()
srv.MaxWebSocketRecvLen = 256
srv.WebSocketThreaded = False
srv.AcceptWebSocketCallback = _acceptWebSocketCallback
#srv.Start(threaded=True)
srv.Start()
print('\n\n** Ready')if srv.IsStarted():
print('Web started')
else:
print('WEB NOT started') -
@pierrot10
if you start lopy inAPmode then it default ip is192.168.*4*.1not 0and what you got on UART? It start without an error?
and please format your future post
http://commonmark.org/help/ -
@pierrot10 Yes, the default IP for LoPy is 192.168.4.1.
If you want, you can also use https://github.com/jczic/MicroDNSSrv to resolve names and connect to the good IP. -
@jczic I'm following your library, discovered some days ago.
Many thanks for sharing! I will dig in a couple of days with it, at the moment I miss some more "elaborated" example (for novices as me).
Will try to make a kind of wifimanager saving/retrieving values to flash in order to connect to a WiFi or keep settings.
Again, many thanks for sharing this, great work! -
@river :')
-
@livius Thank a lot, it really better!!!! It work!!!
Sorry for the format. I edit my post but it did let me to manually add the 3 ```. I will take to not do it again for sure.I am very new with pycom, I started this week-end.
My goal is to have a very simple web server. The goal is when I connect to the Poly4 as AP, it automatically redirect to the /www/index.html.
Is possible to do it?
Additionnaly, I add a pdf.jpg into the folder /www/ and I can not sync it. However, I edit my global and project setting and I add jpg and pdf to the filed
sync_file_typesDid I missed to modify something in the setting?
Next step, I will edit my pysense project and try to integrate the web server, but for now I try to make this project link text working.
Many thank fro your help
-
@jczic Actually, I changed
srv.Start(threaded=True)to
srv.Start(threaded=False)then I changed again to
srv.Start(threaded=True)and I synced and my terminal printed me that error
Reading file status [1/3] Writing file main.py [2/3] Writing file www/pdf.jpg Upload failed. Please reboot your device manually.I also wonder why
if srv.IsStarted(): print('Web started') else: print('WEB NOT started')it always return me
WEB NOT startedwhile it the server is started as I can print a page from 192.168.4.1 ??
Thank for your clarification and your help!!!
Cheers -
@pierrot10
For "WEB NOT started", if you starts MicroWebSrv in threaded mode, you can call IsStarted() function after a little instant because a thread must be started to change the result of IsStarted() to true.
For your terminal error, I don't understand... Sorry :/ -
@jczic Thank a lot for your reply. Yes, I moved IsStarted to another instruction and I got the right message. My Lopy4 act as an AP and the SSID is LoPy4. Do you have any idea, how, it can open a browser and display /www/index.html, as soon as I am connected to my LoPy4 network?
I am very happy, because I could successfully add your library to my sensor project (pysense). No worries for the images. It's not important for the moment, but I will have find.... :o) -
@pierrot10 You want to make a captive portal ?
But for the moment, you can use https://github.com/jczic/MicroDNSSrv because LoPy and others Pycom modules have not DNS server to resolve names :) -
@jczic :o), what do you meen by
You want to make a captive portal ?I would like to display basic information about my node. Because my Lopy4 is LoRa Node. So when the owner is close to the node, he connect to the SSID and he got basic information. But for that I have to write the index.html page with those basic information. In order to make it simple for the user, when he is connected to the SSID, his smartphone browser open and display the info without an additionnal action from the user, excepted to be connected to the SSID.
Thank for the link microDNSSrv.py.
I will look at this, for sure -
@pierrot10 Okay yes, I see.
But at the moment, this is not possible with MicroDNSSrv. I must to add special domaine name like "apple" etc... to automatically open a popup window on smartphones and computers who connects to Wi-Fi AP.
But now, you must to start MicroDNSSrv to resolve names ...
You can open a browser and type a domain name (or catch * wildcards domains). -
@pierrot10 Sorry pierrot but that works (I have just tested) :)
You must to configure MicroDNSServer to respond to all domains with your IP :from microDNSSrv import MicroDNSSrv srv = MicroDNSSrv.Create( { "*" : "192.168.4.1" } )and you must to configure MicroWebSrv with a redirection on a "not found" page :
srv.SetNotFoundPageUrl('my-captive-portal.mydevice.com')If you want to change the default IP and configuration, try this complet code in main.py :
from microWebSrv import MicroWebSrv # ---------------------------------------------------------------------------- def _httpHandlerTestGet(httpClient, httpResponse) : content = """\ <!DOCTYPE html> <html lang=fr> <head> <meta charset="UTF-8" /> <title>TEST GET</title> </head> <body> <h1>TEST GET</h1> Client IP address = %s <br /> <form action="/test" method="post" accept-charset="ISO-8859-1"> First name: <input type="text" name="firstname"><br /> Last name: <input type="text" name="lastname"><br /> <input type="submit" value="Submit"> </form> </body> </html> """ % httpClient.GetIPAddr() httpResponse.WriteResponseOk( headers = None, contentType = "text/html", contentCharset = "UTF-8", content = content ) def _httpHandlerTestPost(httpClient, httpResponse) : formData = httpClient.ReadRequestPostedFormData() firstname = formData["firstname"] lastname = formData["lastname"] content = """\ <!DOCTYPE html> <html lang=fr> <head> <meta charset="UTF-8" /> <title>TEST POST</title> </head> <body> <h1>TEST POST</h1> Firstname = %s<br /> Lastname = %s<br /> </body> </html> """ % ( MicroWebSrv.HTMLEscape(firstname), MicroWebSrv.HTMLEscape(lastname) ) httpResponse.WriteResponseOk( headers = None, contentType = "text/html", contentCharset = "UTF-8", content = content ) # ---------------------------------------------------------------------------- def _acceptWebSocketCallback(webSocket, httpClient) : print("WS ACCEPT") webSocket.RecvTextCallback = _recvTextCallback webSocket.RecvBinaryCallback = _recvBinaryCallback webSocket.ClosedCallback = _closedCallback def _recvTextCallback(webSocket, msg) : print("WS RECV TEXT : %s" % msg) webSocket.SendText("Reply for %s" % msg) def _recvBinaryCallback(webSocket, data) : print("WS RECV DATA : %s" % data) def _closedCallback(webSocket) : print("WS CLOSED") # ---------------------------------------------------------------------------- routeHandlers = [ ( "/test", "GET", _httpHandlerTestGet ), ( "/test", "POST", _httpHandlerTestPost ) ] from network import WLAN wlan = WLAN(); wlan.init(mode=WLAN.AP, ssid='MYDEVICE WIFI', auth=(WLAN.WPA2, 'azerty123')) wlan.ifconfig( id = 1, config = ('10.0.0.254', '255.255.255.0', '10.0.0.254', '10.0.0.254' ) ) srv = MicroWebSrv(routeHandlers=routeHandlers) srv.SetNotFoundPageUrl('my-captive-portal.mydevice.com') srv.MaxWebSocketRecvLen = 256 srv.WebSocketThreaded = False srv.AcceptWebSocketCallback = _acceptWebSocketCallback srv.Start() from microDNSSrv import MicroDNSSrv srv = MicroDNSSrv.Create( { "*" : "10.0.0.254" } ) # ----------------------------------------------------------------------------Just connect your computer or smartphone to wifi MYDEVICE WIFI with pass azerty123 and a captive popup will be opened on your main page :)
-
@jczic That great!!!! Thank, I will try it later!!!!! Thank
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better 💗
Register Login