# Temperatur-Server mit LM75A
# Zum Beenden des Server-Programms: Ctrl-C.
# Vor dem Neustart Hard Boot mit Reset-Taster auslösen!

import network
import socket
from machine import Pin, I2C
from time import time


# Wlan-Zugangsdaten; hier Ihre Wlan-Daten eintragen:
ssid = 'mipamipa'
password = 'Asdfghjkl1234'

# Konfiguration von I2C/LM75A
i2c = I2C(scl=Pin(22), sda=Pin(21), freq= 100000)  
adr = 0x48  # 7-Bit-Adresse im HEX-Format

def messwert():
  rohwert = i2c.readfrom_mem(adr, 0, 2)  
  temp_wert = rohwert[0] + rohwert[1]/256
  return str(temp_wert)

def html():
  return '''  <html>
        <head>
          <title>Temperaturmessung</title>
        </head>
                <body>
                  <h1>Temperatur:
  '''                             + messwert() + '''
                      Grad Celsius</h1>
                </body>
              </html>
  '''

def http_header():
  return '''HTTP/1.1 200 OK\r
Content-Type: text/html\r
Connection: close\r
\r
'''

# Konfiguration des Wlans:
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)
time0 = time()
while (not station.isconnected()) and (time() - time0 < 5):
  pass

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

  # Daten holen
  counter = 0
  while True:
    connection, addr = s.accept()
    print("Client connected: ", addr)

    connection.send(http_header())
    connection.send(html())
    connection.close()

station.active(False)
print('Wlan deactivated')
print('Please reset!')