/ examples / requests_advanced_cellular.py
requests_advanced_cellular.py
 1  # pylint: disable=unused-import
 2  import time
 3  import board
 4  import busio
 5  import digitalio
 6  from adafruit_fona.adafruit_fona import FONA
 7  from adafruit_fona.fona_3g import FONA3G
 8  import adafruit_fona.adafruit_fona_network as network
 9  import adafruit_fona.adafruit_fona_socket as cellular_socket
10  import adafruit_requests as requests
11  
12  # Get GPRS details and more from a secrets.py file
13  try:
14      from secrets import secrets
15  except ImportError:
16      print("GPRS secrets are kept in secrets.py, please add them there!")
17      raise
18  
19  # Create a serial connection for the FONA connection
20  uart = busio.UART(board.TX, board.RX)
21  rst = digitalio.DigitalInOut(board.D9)
22  
23  # Use this for FONA800 and FONA808
24  # fona = FONA(uart, rst)
25  
26  # Use this for FONA3G
27  fona = FONA3G(uart, rst)
28  
29  # Initialize cellular data network
30  network = network.CELLULAR(
31      fona, (secrets["apn"], secrets["apn_username"], secrets["apn_password"])
32  )
33  
34  while not network.is_attached:
35      print("Attaching to network...")
36      time.sleep(0.5)
37  print("Attached!")
38  
39  while not network.is_connected:
40      print("Connecting to network...")
41      network.connect()
42      time.sleep(0.5)
43  print("Network Connected!")
44  
45  # Initialize a requests object with a socket and cellular interface
46  requests.set_socket(cellular_socket, fona)
47  
48  JSON_GET_URL = "http://httpbin.org/get"
49  
50  # Define a custom header as a dict.
51  headers = {"user-agent": "blinka/1.0.0"}
52  
53  print("Fetching JSON data from %s..." % JSON_GET_URL)
54  response = requests.get(JSON_GET_URL, headers=headers)
55  print("-" * 60)
56  
57  json_data = response.json()
58  headers = json_data["headers"]
59  print("Response's Custom User-Agent Header: {0}".format(headers["User-Agent"]))
60  print("-" * 60)
61  
62  # Read Response's HTTP status code
63  print("Response HTTP Status Code: ", response.status_code)
64  print("-" * 60)
65  
66  # Read Response, as raw bytes instead of pretty text
67  print("Raw Response: ", response.content)
68  
69  # Close, delete and collect the response data
70  response.close()