Networking#
Now the standard networking resources - network
, socket
, requests
, … - are available to the client.
Note: No support for select
.
%connect wifi-client
Connected to wifi-client @ serial:///dev/ttyACM0
IP#
import network
ip = network.WLAN(network.STA_IF).ifconfig()[0]
print("IP address:", ip)
IP address: 10.39.40.169
Webserver#
Run the cell below, then click on the URL (“waiting for connection at …”).
import socket
import network
ip = network.WLAN(network.STA_IF).ifconfig()[0]
s = socket.socket()
ai = socket.getaddrinfo("0.0.0.0", 80)
addr = ai[0][-1]
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
s.listen(2)
print("waiting for connection at http://{}".format(ip))
for i in range(6):
ss, addr = s.accept()
print("connected from", addr)
req = ss.recv(1024)
if i < 4:
ss.send('Hello from WiFi Coprocessor, serving request # {}!'.format(i+1).encode())
else:
ss.send(b'So long! Server shutting down.')
ss.close()
s.close()
print("DONE")
waiting for connection at http://10.39.40.169
connected from ('10.39.40.114', 63858)
connected from ('10.39.40.114', 63859)
connected from ('10.39.40.114', 63860)
connected from ('10.39.40.114', 63861)
connected from ('10.39.40.114', 63862)
connected from ('10.39.40.114', 63863)
DONE
Requests#
Example: Weather data from https://home.openweathermap.org/
Note: Create an account and define openweathermap_apiid
in secrets.py
.
from requests import get
from secrets import openweathermap_apiid
cnt = 1
url = "http://api.openweathermap.org/data/2.5/find?lat=38.5&lon=-120&cnt={}&appid={}".format(cnt, openweathermap_apiid)
j = get(url).json()
for k,v in j.get('list')[0].items():
print("{:8} {}".format(k,v))
coord {'lat': 38.4646, 'lon': -120.0399}
wind {'speed': 1.2, 'deg': 167}
rain None
weather ({'id': 802, 'description': 'scattered clouds', 'icon': '03d', 'main': 'Clouds'},)
dt 1637683849
snow None
clouds {'all': 28}
main {'feels_like': 274.32, 'pressure': 1022, 'temp_min': 268.16, 'humidity': 64, 'temp_max': 277.33, 'temp': 274.32}
name Bear Valley
sys {'country': 'US'}
id 5326968