import ESP8266WebServer
import network
import machine

GPIO_NUM = 15 # Pin name (D8)

# Wi-Fi configuration
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('SSID', 'password')
while not sta_if.isconnected():
    pass

# Show IP address
print("Server started @", sta_if.ifconfig()[0])

# Get pin object for controlling builtin LED
pin = machine.Pin(GPIO_NUM, machine.Pin.OUT)

# Turn LED on (Default)
pin.on()

# Handler for path "/cmd?led=[on|off]"    
def handleCmd(socket, args):
    if 'led1' in args:
        if args['led1'] == 'off':
            pin.off()
        elif args['led1'] == 'on':
            pin.on()
        ESP8266WebServer.ok(socket, "200", args["led1"])
    else:
        ESP8266WebServer.err(socket, "400", "Bad Request")

# Start the server @ port 8899
ESP8266WebServer.begin(8899)

# Register handler for each path
ESP8266WebServer.onPath("/cmd", handleCmd)

try:
    while True:
        # Let server process requests
        ESP8266WebServer.handleClient()
except:
    ESP8266WebServer.close()
