/ examples / requests_simpletest_cellular.py
requests_simpletest_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.D4)
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  TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html"
49  JSON_GET_URL = "http://httpbin.org/get"
50  JSON_POST_URL = "http://httpbin.org/post"
51  
52  print("Fetching text from %s" % TEXT_URL)
53  response = requests.get(TEXT_URL)
54  print("-" * 40)
55  
56  print("Text Response: ", response.text)
57  print("-" * 40)
58  response.close()
59  
60  print("Fetching JSON data from %s" % JSON_GET_URL)
61  response = requests.get(JSON_GET_URL)
62  print("-" * 40)
63  
64  print("JSON Response: ", response.json())
65  print("-" * 40)
66  response.close()
67  
68  data = "31F"
69  print("POSTing data to {0}: {1}".format(JSON_POST_URL, data))
70  response = requests.post(JSON_POST_URL, data=data)
71  print("-" * 40)
72  
73  json_resp = response.json()
74  # Parse out the 'data' key from json_resp dict.
75  print("Data received from server:", json_resp["data"])
76  print("-" * 40)
77  response.close()
78  
79  json_data = {"Date": "July 25, 2019"}
80  print("POSTing data to {0}: {1}".format(JSON_POST_URL, json_data))
81  response = requests.post(JSON_POST_URL, json=json_data)
82  print("-" * 40)
83  
84  json_resp = response.json()
85  # Parse out the 'json' key from json_resp dict.
86  print("JSON Data received from server:", json_resp["json"])
87  print("-" * 40)
88  response.close()