# Server für Websites (Basis-Form, ohne Exceptions etc.)

import network
import socket
from time import time

ssid = 'mipamipa'
password = 'Asdfghjkl1234'

def http_header(extension):
  c_type = ''  # ??????????????????????????????????????????????????
  if extension == 'jpg':
    c_type = 'image/jpeg'
  if extension == 'htm':
    c_type = 'text/html'  
  return '''HTTP/1.1 200 OK\r
Content-Type: ''' + c_type + '''\r
Connection: close\r
\r
'''

# Konfiguration des Wlans:
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password) # hier Ihre WLan-Daten eintragen!
time0 = time()
while (station.isconnected() == False) and (time() - time0 < 5):
  pass

if station.isconnected():
  print('Wlan connected')
  print(station.ifconfig()) # zur Information
  s=socket.socket() # Socket des Servers
  s.bind(('', 80))
  s.listen(5) #backlog
  print('Server listening')
  print('---------------------------------------------------------------')

  while True:
      connection, addr = s.accept()
      print("Client connected: ", addr) # manchmal connected ohne Senden eines HTML-Requests
      
      # Request empfangen
      request = ''
      block_size = 512
      while True:
        data = connection.recv(block_size)
        request = request + str(data, 'UTF-8')        
        if request.find('\r\n\r\n') >= 0: # Ende des Requests gefunden
          break

      # Request anzeigen und auswerten
      print('Request: ')
      print(request)
      get = request.partition('GET /')[2]
      filename = get.partition(' ')[0]

      extension = filename.partition('.')[2]
      # print('Requested File: ', filename, ', Extension: ', extension)
      
      # HTTP-Header senden...        
      connection.send(http_header(extension))  

      # HTML-Datei oder Bild-Datei senden...
      if extension == 'htm' or extension == 'jpg':
        f = open(filename, 'rb') # Txt-Datei oder Bild-Datei oder...
        block_size = 512
        while True:
          data = f.read(block_size)  
          connection.send(data)
          if len(data) < block_size:
            break  
        f.close()
    
      connection.close()
      del connection
      print('---------------------------------------------------------------')

 
if station.isconnected():
  station.disconnect()  
print('Wlan not connected')
station.active(False)
print('Wlan deactivated')
print('Please reboot!')

    
