# Import the microdot web server library from microdot import Microdot, Response from simpletemplate import render_template # We also need network access so clients can connect to our web page... import network # The thermocouple sensor library from machine import Pin from max6675 import MAX6675 # And the MQTT library so we can control smartplugs from umqttsimple import MQTTClient # Make sure we're connected to the network wlan = network.WLAN(network.STA_IF) if not wlan.isconnected(): # If we're not connected, try to connect to Tufts_Wireless: wlan.active(True) ssid = "Tufts_Wireless" print("Connecting to {}...".format(ssid)) wlan.connect(ssid) while not wlan.isconnected(): print('.', end='') sleep(1) # Print out our IP address so we know where to point the web browser! ip_address = wlan.ifconfig()[0] print("Site will be accessible at http://{}".format(ip_address)) # Set up the thermocouple therm = MAX6675(cs=Pin(12), sck=Pin(14), so=Pin(13)) # Set up our connection to the MQTT server mqttclient = MQTTClient("esp32-UTLN", "en1-pi.eecs.tufts.edu") mqttclient.connect() SMARTPLUG_TOPIC = "ESPURNA-XXXXXX/relay/0/set" # Set up the microdot server app = Microdot() # Main page @app.route('/') def index(request): return Response.send_file('popcorn.html') # CSS style file @app.route('/style.css') def style(request): return Response.send_file('style.css') # Monitoring page @app.route('/monitor') def monitor(request): # We can do wahtever we want here, like start the popcorn popper # However, we shouldn't sleep or do things that will take a long time, # because the user is waiting for us to return a web page mqttclient.publish(SMARTPLUG_TOPIC, '1') # We can use request.args to read the values sent from the HTML form, e.g., n = request.args['quantity'] # And then we can use that number (or anything else) as a template parameter # to customize what appears on the page. return Response(body=render_template('monitor.html', quantity=n), headers={'Content-Type': 'text/html'}) # Data update which returns the current temperature @app.route('/data') def data(request): # Here we're just returning a Python dictionary, which gets automatically converted to JSON return {"temp":therm.read() * 9 / 5 + 32} # Stop, which just turns off the popper and redirects back to the home page @app.route('/stop') def stop(request): mqttclient.publish(SMARTPLUG_TOPIC, '0') return Response.redirect('/') # Start the server running # port=80 will make it run on the default HTTP port like a normal web server # debug=True will make it print out useful information to the REPL app.run(port=80, debug=True)