Advertisement
Guest User

Pico Web Server

a guest
Sep 25th, 2022
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.57 KB | Science | 0 0
  1. #!/usr/bin/python3
  2. from time import sleep
  3. from os import stat
  4. from random import randrange as rng # using this for random cache time between 1 and 2 weeks
  5. from gc import mem_free as fram
  6. from gc import collect as clearRAM
  7. import network
  8. import socket
  9.  
  10. def file_exists(filename):
  11.     try:
  12.         return (stat(filename)[0] & 0x4000) == 0
  13.     except OSError:
  14.         return False
  15.  
  16. ssid="Your's WiFi"
  17. password="12345678"
  18. # WOW much security; This is fine...
  19.  
  20. wlan = network.WLAN(network.STA_IF)
  21. wlan.active(True)
  22. wlan.connect(ssid, password)
  23.  
  24. max_wait = 10
  25. while max_wait > 0:
  26.     if wlan.status() < 0 or wlan.status() >= 3:
  27.         break
  28.     max_wait -= 1
  29.     print('Waiting for connection...')
  30.     sleep(1)
  31.  
  32. if wlan.status() != 3:
  33.     raise RuntimeError('network connection failed')
  34. else:
  35.     print('connected')
  36.     status = wlan.ifconfig()
  37.     print( 'ip = ' + status[0] )
  38.  
  39. addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
  40.  
  41. s = socket.socket()
  42. s.bind(addr)
  43. s.listen(1)
  44.  
  45. print('Listening on', addr,'\n\n')
  46.  
  47. while True:
  48.     try:
  49.         cl, addr = s.accept()
  50.         print('Client connected from', addr)
  51.         request = cl.recv(1024)
  52.  
  53.         request = str(request)
  54.         request=request.split("\\r\\n")[0].split(' ')
  55.  
  56.         if len(request) > 0:
  57.             if request[0]=="b'GET":
  58.                 if request[1] == "/":
  59.                     request[1] = "/index.html"
  60.                 if request[1] == "/favicon.ico":
  61.                     request[1] = "/favicon.png"
  62.  
  63.                 file='www'+request[1]
  64.                 if file_exists(file):
  65.                     header='HTTP/1.0 200 OK\r\nContent-type: '
  66.                     if request[1].find('.html') > 0:
  67.                         header+='text/html'
  68.                     elif request[1].find('.css') > 0:
  69.                         header+='text/css'
  70.                     elif request[1].find('.js') > 0:
  71.                         header+='application/javascript'
  72.                     elif request[1].find('.webp') > 0:
  73.                         header+='image/webp'
  74.                     elif request[1].find('.gif') > 0:
  75.                         header+='image/gif'
  76.                     elif request[1].find('.png') > 0:
  77.                         header+='image/png'
  78.                     elif request[1].find('.jpg') > 0:
  79.                         header+='image/jpeg'
  80.                     elif request[1].find('.gif') > 0:
  81.                         header+='image/gif'
  82.                     else:
  83.                         print('Not Implemented:', file,'\n')
  84.                         cl.send(header+'text/plain\r\n\r\nFile type not impliemted')
  85.                         cl.close()
  86.                         print('Closed connection\n')
  87.                         continue
  88.  
  89.                     end=stat(file)[6]
  90.                     print('Open',end,':',file,'with', fram())
  91.                     if(end*1.1 < fram()): # end*1.1 is to be sure we are not completely out of memory, in theory you do not need the *1.1
  92.                         cl.send(header+'\r\nContent-Language: pt-BR\r\nCache-Control: max-age='+str(rng(604800,1209600))+'\r\n')
  93.                         with open(file, 'rb') as f:
  94.                             cl.send('Content-Length:'+str(end))
  95.                             f=f.read()
  96.                             cl.send('\r\n\r\n')
  97.                             cl.sendall(f)
  98.                     else:
  99.                         print("Low Ram: Offload",file,"to alt server")
  100.                         # this is gonna be a issue if it happens to index.html
  101.                         cl.send('HTTP/1.0 301 OK\r\nLocation: http://10.0.0.25:8080/thermostat/'+file[4:])
  102.                 elif request[1].find('.json') >0:
  103.                     print('Emulate:',file)
  104.                     if file[0:13] == "www/temp.json":
  105.                         json='{"temp":"20000","tube1":0,"tube2":1,"relay1":0,"relay2":1}'
  106.                     elif file[0:15] == "www/config.json":
  107.                         json='{"target": 72.5, "format": "F", "auxon": 1, "auxenabled": 1, "enabled": 1, "auxoff": 2, "trigger": 1, "sunset": 30, "night": 0, "day": 0, "sunrise": 90}'
  108.                     elif file[0:12] == "www/sun.json":
  109.                         json='{"rise":{"time":"6:59 AM","hour":6,"minute":59,"stamp":1664103540},"set":{"time":"6:56 PM","hour":18,"minute":56,"stamp":1664146560}}'
  110.                     elif file[0:13] == "www/cron.json":
  111.                         json='[{"enable":false,"days":[6,0],"time":{"start":{"h":22,"m":30},"end":{"h":23,"m":59}},"offset":-0.45,"name":"1. Chad wants cooler for sleep on weekend"},{"enable":false,"days":[1,0],"time":{"start":{"h":0,"m":0},"end":{"h":3,"m":0}},"offset":-0.45,"name":"2. Chad wants cooler for sleep on weekend"},{"enable":true,"days":[1,2,3,4,5,6,0],"time":{"start":{"h":4,"m":0},"end":{"h":10,"m":0}},"offset":-0.5,"name":"Lower temp in early morning"}]'
  112.                     else:
  113.                         json='{"Error":"File not implemented, typo?"}'
  114.                     cl.send('HTTP/1.0 200 OK\r\nContent-type: application/json\r\nContent-Length: '+str(len(json))+'\r\nCache-Control: no-cache\r\n\r\n'+json)
  115.                 else:
  116.                     print('404 Error',file)
  117.                     cl.send('HTTP/1.0 404 OK\r\nContent-type: text/html\r\n\r\n<html><head><title>404 Error</title></head><body>404 File not found</body></html>')
  118.             elif request[0]=="b'POST":
  119.                 print('Not Implemented: todo')
  120.             else:
  121.                 print('Say what?:',request)
  122.         else:
  123.             print('Say what?:',request)
  124.         cl.close()
  125.         print('Closed connection\n')
  126.         clearRAM()
  127.  
  128.     except OSError as e:
  129.         cl.close()
  130.         print('Connection closed; Error:',e,'\n')
  131.  
  132.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement