I just started with NodeMCU and MicroPython. I have followed this tutorial (https://docs.micropython.org/en/latest/ ... k_tcp.html) to set up a HTTP server for simple LED switching.
My boot.py looks like this:
Code: Select all
import os
try:
import usocket as socket
except:
import socket
from machine import Pin
import network
import esp
esp.osdebug(None)
import gc
gc.collect()
ssid = 'my wifi SSID'
password = 'my wifi password'
station = network.WLAN(network.STA_IF)
station.active(True)
station.ifconfig
station.connect(ssid, password)
while station.isconnected() == False:
pass
print('Connection successful')
print(station.ifconfig())
Code: Select all
def web_page():
if led.value() == 1:
gpio_state="ON"
else:
gpio_state="OFF"
html = """<html><head> <title>ESP Web Server</title> <meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="data:,"> <style>html{font-family: Helvetica; display:inline-block; margin: 0px auto; text-align: center;}
h1{color: #0F3376; padding: 2vh;}p{font-size: 1.5rem;}.button{display: inline-block; background-color: #e7bd3b; border: none;
border-radius: 4px; color: white; padding: 16px 40px; text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}
.button2{background-color: #4286f4;}</style></head><body> <h1>ESP Web Server</h1>
<p>GPIO state: <strong>""" + gpio_state + """</strong></p><p><a href="/?led=on"><button class="button">ON</button></a></p>
<p><a href="/?led=off"><button class="button button2">OFF</button></a></p></body></html>"""
return html
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)
while True:
conn, addr = s.accept()
print('Got a connection from %s' % str(addr))
request = conn.recv(1024)
request = str(request)
print('Content = %s' % request)
led_on = request.find('/?led=on')
led_off = request.find('/?led=off')
if led_on == 6:
print('LED ON')
led.value(1)
if led_off == 6:
print('LED OFF')
led.value(0)
response = web_page()
conn.send('HTTP/1.1 200 OK\n')
conn.send('Content-Type: text/html\n')
conn.send('Connection: close\n\n')
conn.sendall(response)
conn.close()
My question is, how do I need to modify my code to be able to access my NodeMCU from anywhere in the world? Do I need a static IP address? I have read that there are several ways to achieve this, first being some port forwarding through the router (unfortunately, I do not have access to the router, and I have several mobile projects in mind where I will need to create NodeMCU server from other WiFi networks where I won't have access to router either). Second, I found that there are some services like aRest and ThingSpeak that somehow allow to do this too, but the libraries required to use them don't seem to be available for MicroPython.
So, what options are there? What's the simplest way to make NodeMCU accessible from anywhere without having to tinker with the router?