|
3 | 3 | import busio
|
4 | 4 | import digitalio
|
5 | 5 | from adafruit_fona.adafruit_fona import FONA
|
6 |
| -import adafruit_fona.adafruit_fona_socket as socket |
| 6 | +import adafruit_fona.adafruit_fona_socket as cellular_socket |
| 7 | +import adafruit_requests as requests |
7 | 8 |
|
8 |
| -SERVER_ADDRESS = ("wifitest.adafruit.com", 80) |
| 9 | +print("FONA WebClient Test") |
| 10 | + |
| 11 | +TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html" |
| 12 | +JSON_URL = "http://api.coindesk.com/v1/bpi/currentprice/USD.json" |
9 | 13 |
|
10 | 14 | # Get GPRS details and more from a secrets.py file
|
11 | 15 | try:
|
|
21 | 25 | rst = digitalio.DigitalInOut(board.D4)
|
22 | 26 |
|
23 | 27 | # Initialize FONA module (this may take a few seconds)
|
24 |
| -fona = FONA(uart, rst, debug=True) |
| 28 | +fona = FONA(uart, rst) |
25 | 29 |
|
26 | 30 | print("Adafruit FONA WebClient Test")
|
27 | 31 |
|
|
34 | 38 | # Bring up GPRS
|
35 | 39 | fona.gprs = True
|
36 | 40 |
|
37 |
| -# Set socket interface |
38 |
| -socket.set_interface(fona) |
39 |
| - |
40 |
| -sock = socket.socket() |
41 |
| - |
42 |
| -print("Connecting to: ", SERVER_ADDRESS[0]) |
43 |
| -sock.connect(SERVER_ADDRESS) |
| 41 | +# Initialize a requests object with a socket and cellular interface |
| 42 | +requests.set_socket(cellular_socket, fona) |
44 | 43 |
|
45 |
| -print("Connected to:", sock.getpeername()) |
46 |
| -time.sleep(7) |
| 44 | +print("My IP address is:", fona.local_ip) |
| 45 | +print( |
| 46 | + "IP lookup adafruit.com: %s" % fona.get_host_by_name("adafruit.com") |
| 47 | +) |
47 | 48 |
|
48 |
| -# Make a HTTP Request |
49 |
| -sock.send(b"GET /testwifi/index.html HTTP/1.1\n") |
50 |
| -sock.send(b"Host: 104.236.193.178") |
51 |
| -sock.send(b"Connection: close\n\n") |
| 49 | +fona._debug = True |
| 50 | +print("Fetching text from", TEXT_URL) |
| 51 | +r = requests.get(TEXT_URL) |
| 52 | +print("-" * 40) |
| 53 | +print(r.text) |
| 54 | +print("-" * 40) |
| 55 | +r.close() |
52 | 56 |
|
53 |
| -bytes_avail = 0 |
54 |
| -while not bytes_avail: |
55 |
| - bytes_avail = sock.available() |
56 |
| - if bytes_avail > 0: |
57 |
| - print("bytes_avail: ", bytes_avail) |
58 |
| - data = sock.recv(bytes_avail) |
59 |
| - print(data.decode()) |
60 |
| - break |
61 |
| - time.sleep(0.05) |
| 57 | +print() |
| 58 | +print("Fetching json from", JSON_URL) |
| 59 | +r = requests.get(JSON_URL) |
| 60 | +print("-" * 40) |
| 61 | +print(r.json()) |
| 62 | +print("-" * 40) |
| 63 | +r.close() |
62 | 64 |
|
63 |
| -sock.close() |
64 |
| -print("Socket connected: ", sock.connected) |
| 65 | +print("Done!") |
0 commit comments