Advertisement
misaalanshori

micropython code

Oct 24th, 2019
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.12 KB | None | 0 0
  1. this is the output on the serial terminal
  2. Content = b'POST /test HTTP/1.1\r\nHost: 192.168.0.29\r\nConnection: keep-alive\r\nContent-Length: 101\r\nCache-Control: max-age=0\r\nOrigin: http://192.168.0.29\r\nUpgrade-Insecure-Requests: 1\r\nContent-Type: application/x-www-form-urlencoded\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\r\nReferer: http://192.168.0.29/test\r\nAccept-Encoding: gzip, d'
  3.  
  4. and this is the modified code (it probably looks like a mess):
  5.  
  6. import gc
  7. import os
  8.  
  9.  
  10. value = 0
  11. string = "HelloWorld"
  12. firstNum = 0.0
  13. secNum = 0.0
  14. calcNum = 0.0
  15. calcError = ""
  16. extraHTML = '<meta name="viewport" content="width=device-width, initial-scale=1"><link rel="icon" href="data:,"><style>html{font-family: Helvetica; display:inline-block; margin: 0px auto; text-align: center;} h1{color: #0F3376; padding: 2vh;}p{font-size: 1.5rem;}.button{display: inline-block; background-color: #e7bd3b; border: none;  border-radius: 4px; color: white; padding: 16px 40px; text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;} .button2{background-color: #4286f4;}</style>'
  17.  
  18. _hextobyte_cache = None
  19.  
  20. def unquote(string):
  21.     """unquote('abc%20def') -> b'abc def'."""
  22.     global _hextobyte_cache
  23.  
  24.     # Note: strings are encoded as UTF-8. This is only an issue if it contains
  25.     # unescaped non-ASCII characters, which URIs should not.
  26.     if not string:
  27.         return b''
  28.  
  29.     if isinstance(string, str):
  30.         string = string.encode('utf-8')
  31.  
  32.     bits = string.split(b'%')
  33.     if len(bits) == 1:
  34.         return string
  35.  
  36.     res = [bits[0]]
  37.     append = res.append
  38.  
  39.     # Build cache for hex to char mapping on-the-fly only for codes
  40.     # that are actually used
  41.     if _hextobyte_cache is None:
  42.         _hextobyte_cache = {}
  43.  
  44.     for item in bits[1:]:
  45.         try:
  46.             code = item[:2]
  47.             char = _hextobyte_cache.get(code)
  48.             if char is None:
  49.                 char = _hextobyte_cache[code] = bytes([int(code, 16)])
  50.             append(char)
  51.             append(item[2:])
  52.         except KeyError:
  53.             append(b'%')
  54.             append(item)
  55.  
  56.     return b''.join(res)
  57.  
  58. def indexpage():
  59.  
  60.   def df():
  61.     s = os.statvfs('//')
  62.     return ('{0} MB'.format((s[0]*s[3])/1048576))
  63.  
  64.   def free(full=False):
  65.     F = gc.mem_free()
  66.     A = gc.mem_alloc()
  67.     T = F+A
  68.     P = '{0:.2f}%'.format(F/T*100)
  69.     if not full: return P
  70.     else : return ('Total:{0} Free:{1} ({2})'.format(T,F,P))
  71.    
  72.   ramrom = "Free Space: " + df() + " Memory Usage: " + free()
  73.  
  74.   html = '''<html>
  75.                 <head>
  76.                     <title>ESP Web Server</title>''' + extraHTML +'''</head>
  77.                 <body>
  78.                     <h1>ESP Web Server on Micropython</h1>
  79.                     <h6>Original code from <a href="https://randomnerdtutorials.com" target="_blank">randomnerdtutorials.com</a>
  80.                     </h6>
  81.                     <h3>
  82.                         <a href="/test">Goto /test</a>
  83.                     </h3>
  84.                     <p>Memory usage: <strong>''' + ramrom + '''</strong>
  85.                     </p>
  86.                     <p>Value: <strong>''' + str(value) + '''</strong>
  87.                     </p>
  88.                     <p>
  89.                         <a href="/?valueadd">
  90.                             <button class="button">increase</button>
  91.                         </a>
  92.                     </p>
  93.                     <p>
  94.                         <a href="/?valuedec">
  95.                             <button class="button button2">Decrease</button>
  96.                         </a>
  97.                     </p>
  98.                     <p>String = <strong>''' + string + '''</strong>
  99.                     </p>
  100.                     <input id="txt" type="text" value="''' + string +'''">
  101.                         <p>
  102.                             <a onclick="location.href=\'/?string=\' + document.getElementById(\'txt\').value + \'EndOfStr\';">
  103.                                 <button class="button button2">setstring</button>
  104.                             </a>
  105.                         </p>
  106.                     </body>
  107.                 </html>'''
  108.   return html
  109.  
  110. def secondpage():
  111.   try:
  112.     calcNum = firstNum * secNum
  113.   except ValueError:
  114.     calcNum = " ValueError Occured"
  115.   html2 = '''<html>
  116.                 <head>
  117.                     <title>FormTest</title>' + extraHTML +'</head>
  118.                 <body>
  119.                     <h1>Forms Test page gengs</h1>
  120.                     <h3>
  121.                     <a href="/">Goto /</a>
  122.                     </h3>
  123.                     <h3>
  124.                     </strong>First Number: ''' + str(firstNum) + ''' </strong>
  125.                     </h3>
  126.                     <h3>
  127.                     </strong>Second Number: ''' + str(secNum) + ''' </strong>
  128.                     </h3>
  129.                     <h3>
  130.                     </strong>Resulting Number: ''' + str(calcNum) + calcError + ''' </strong>
  131.                     </h3>
  132.                     </br>
  133.                     <form action="/test">First Number:<br>
  134.                         <input type="text" name="firstnum" value="420">
  135.                         <br>Multiplied by<br>Second Number:<br>
  136.                         <input type="text" name="secondnum" value="420">
  137.                         <br>
  138.                         <br>
  139.                         <input type="submit" value="Submit">
  140.                     </form>
  141.                     <br>
  142.                     <form action="/test" method="POST">
  143.                       First name: <input type="text" name="fname"><br>
  144.                       Last name: <input type="text" name="lname"><br>
  145.                       <input type="submit" value="Submit">
  146.                     </form>
  147.  
  148.                 </body>
  149.             </html>'''
  150.   return html2
  151.  
  152. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  153. s.bind(('', 80))
  154. s.listen(5)
  155.  
  156. while True:
  157.   conn, addr = s.accept()
  158.   print('Got a connection from %s' % str(addr))
  159.   request = conn.recv(1024)
  160.   request = str(request)
  161.   print('Content = %s' % request)
  162.   valueadd = request.find('/?valueadd')
  163.   valuedec = request.find('/?valuedec')
  164.   chstring = request.find('/?string=')
  165.   strend = request.find('EndOfStr')
  166.   getFirstNum = request.find('?firstnum=')
  167.   getFirstNumEnd = request.find('&secondnum')
  168.   getSecondNum = request.find('&secondnum=')
  169.   getRequestEnd = request.find(" HTTP/")
  170.  
  171.   if valueadd == 6:
  172.     value += 1
  173.   if valuedec == 6:
  174.     value -= 1
  175.   if chstring == 6:
  176.     string = request[15:int(strend)]
  177.   if getFirstNum == 11:
  178.     try:
  179.       calcError = ""
  180.       diff = getSecondNum + 11
  181.       firstNum = float(request[21:getFirstNumEnd])
  182.       secNum = float(request[diff:getRequestEnd])
  183.     except ValueError:
  184.       calcError = " ValueError Occured"
  185.   if request[6:11] == "/test":
  186.     response = secondpage()
  187.   else:
  188.     response = indexpage()
  189.    
  190.   conn.send('HTTP/1.1 200 OK\n')
  191.   conn.send('Content-Type: text/html\n')
  192.   conn.send('Connection: close\n\n')
  193.   conn.sendall(response)
  194.   conn.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement