#file: pico2w-ledserver #encoding: utf-8 import machine import network import json import socket import rp2 from time import sleep from machine import Pin f = open('wlan.json', 'r') c = json.load(f) ssid = c['ssid'] passwd = c['passwd'] rp2.country(c['regio']) led = Pin("LED", Pin.OUT) ledstates = {'False':'ausgeschaltet','True':'eingeschaltet'} def toogle_LED(state): if state: led.on() else: led.off() def load_html(): try: f = open('index.html','r') print(f'f={f}') page = f.read() except IOError as x: print(f'I/O-Fehler: {x}') finally: if f != None: f.close() return page def connect(): wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect(ssid,passwd) while not wlan.isconnected(): print('Waiting for connection...') sleep(1) print(f'connected={wlan.isconnected()}') return wlan.ifconfig() # Bindet einen Socket an die Verbindung def open_socket(ip): # Socket öffnen s = socket.socket() address = socket.getaddrinfo('0.0.0.0',80)[0][-1] print(f'address={address}') s.bind(address) s.listen(1) return s def serve(s): page = load_html() print(f'page={page}') running = True ledstatus = False req_count = 0 toogle_LED(ledstatus) #Start web server while running: client, address = s.accept() request = client.recv(1024) request = str(request) req_count += 1 print(f'req_count={req_count}') try: request = request.split()[1] except IndexError: pass if request == '/on': print('Kommando on') ledstatus = True elif request =='/off': print('Kommando off') ledstatus = False elif request =='/stop': print('stopping') running = False ledstatus = False toogle_LED(ledstatus) client.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n'.encode('utf-8')) state = ledstates[str(ledstatus)] print(f'status={state}') page = page.format(state) client.send(page.encode('utf-8')) client.close() ip = connect() print(f'ip={ip}') s = open_socket(ip) serve(s) s.close() toogle_LED(False)