Skip to content

Commit 7731136

Browse files
feat: add HTTP examples (#2)
1 parent 2d06b30 commit 7731136

File tree

2 files changed

+375
-0
lines changed

2 files changed

+375
-0
lines changed

examples/http_requests_example.py

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
"""
2+
Example code for publising data to any server with using HTTP methods.
3+
"""
4+
5+
import json
6+
import time
7+
8+
from core.modem import Modem
9+
from core.status import Status
10+
11+
def handle_cellular_network_connection():
12+
"""This function handles the connection to cellular network connection.
13+
"""
14+
# Ask for return from the modem.
15+
modem.check_modem_communication()
16+
# Send APN details.
17+
modem.set_modem_apn(cid=1, apn="super")
18+
# Try to get a operator response for 10 times.
19+
for _index in range(0, 10):
20+
# Check if there is a connection to any operator.
21+
response = modem.get_operator_information()
22+
if response["status"] == Status.SUCCESS:
23+
return
24+
# Wait for 1 second.
25+
time.sleep(1)
26+
27+
def prepare_http_connection():
28+
"""This function prepares HTTP connection for modem.
29+
"""
30+
# Set the first HTTP context.
31+
modem.set_modem_http_context_id()
32+
# Activate PDP.
33+
modem.activate_pdp_context()
34+
35+
def prepare_http_with_query(host_url, query_string=""):
36+
"""Sets the modem's HTTP server address.
37+
38+
Args:
39+
host_url (str): Server address to send request.
40+
query_string (str, optional): Query payload for the server. Defaults to "".
41+
"""
42+
# Add query to the server URL.
43+
url_to_post = host_url + "/?" + query_string
44+
# Set the HTTP url.
45+
modem.set_modem_http_server_url(url=url_to_post)
46+
47+
def send_post_request(server_url, data_dict, query_string=""):
48+
"""POST request to the HTTP server with a payload and optional query.
49+
50+
Args:
51+
server_url (str): Server address to send request.
52+
data_dict (dict): The data for the request as dictionary.
53+
query_string (str, optional): Query payload for the server. Defaults to "".
54+
"""
55+
# Configure the HTTP address.
56+
prepare_http_with_query(server_url, query_string)
57+
# Convert to data to JSON.
58+
data_to_post = json.dumps(data_dict)
59+
# Send a post request to the URL.
60+
print("POST Request: ", modem.http_post_request(data=data_to_post))
61+
# Wait for six seconds before the next operation.
62+
time.sleep(6)
63+
64+
def send_get_request(server_url, query_string=""):
65+
"""GET request to the HTTP server with optional query.
66+
67+
Args:
68+
server_url (str): Server address to send request.
69+
query_string (str, optional): Query payload for the server. Defaults to "".
70+
"""
71+
# Configure the HTTP address.
72+
prepare_http_with_query(server_url, query_string)
73+
# Send a GET request.
74+
print("GET Request: ", modem.http_get_request())
75+
# Wait for six seconds before the next operation.
76+
time.sleep(6)
77+
78+
def send_put_request(server_url, data_dict, query_string=""):
79+
"""PUT request to the HTTP server with a payload and optional query.
80+
81+
Args:
82+
server_url (str): Server address to send request.
83+
data_dict (dict): The data for the request as dictionary.
84+
query_string (str, optional): Query payload for the server. Defaults to "".
85+
"""
86+
# Configure the HTTP address.
87+
prepare_http_with_query(server_url, query_string)
88+
# Convert to data to JSON.
89+
data_to_post = json.dumps(data_dict)
90+
# Send a PUT request.
91+
print("PUT Request: ", modem.http_put_request(data_to_post))
92+
# Wait for six seconds before the next operation.
93+
time.sleep(6)
94+
95+
96+
if __name__ == "__main__":
97+
# Initilizate the modem.
98+
modem = Modem({})
99+
# Connect to a cellular network.
100+
handle_cellular_network_connection()
101+
# Prepare for the HTTP context.
102+
prepare_http_connection()
103+
# Select a HOST for testing purposes.
104+
HOST = "https://webhook.site/6112efa6-4f8c-4bdb-8fa3-5787cc02f80a"
105+
# Send a POST request to the server.
106+
send_post_request(HOST, {"ProjectTopic": "PicocellHTTPExample"}, "device=Pico&try=0")
107+
# Send a GET request to the server.
108+
send_get_request(HOST, "company=Sixfab&course=Picocell")
109+
# Send PUT request.
110+
send_put_request(HOST, {"Temperature(*C)": 28}, "sensor=Garden1")
Lines changed: 265 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,265 @@
1+
"""
2+
Example code for publising data to any server with using HTTP methods by using manager class.
3+
"""
4+
5+
import json
6+
import time
7+
8+
from core.modem import Modem
9+
from core.status import Status
10+
from core.manager import StateManager, Step
11+
12+
def step_for_setting_server_url(modem_object, next_function, url=None, query=""):
13+
"""This function returns a step for setting server's URL with a query.
14+
15+
Args:
16+
modem_object (Modem): The modem instance to call methods.
17+
next_function (string): Next step's name if the step got success.
18+
url (str, optional): URL for the host. Defaults to None.
19+
query (str, optional): Query for the server. Defaults to "".
20+
21+
Returns:
22+
Step: The step instance for setting server URL in the modem.
23+
"""
24+
25+
url_with_query = url + "/?" + query
26+
# Set-up the steps for state manager.
27+
step_set_server_url = Step(
28+
function=modem_object.set_modem_http_server_url,
29+
name="set_server_url",
30+
success=next_function,
31+
fail="failure",
32+
function_params={"url": url_with_query},
33+
cachable=True
34+
)
35+
36+
return step_set_server_url
37+
38+
39+
def prepare_communication_for_http(modem_object):
40+
"""A function to register the cellular network
41+
and activate the PDP.
42+
43+
Args:
44+
modem_object (Modem): The modem instance to call methods.
45+
46+
Returns:
47+
dict: A dictionary which has the results inside.
48+
"""
49+
50+
# Set-up the steps for state manager.
51+
step_network_reg = Step(
52+
function=modem_object.register_network,
53+
name="register_network",
54+
success="pdp_deactivate",
55+
fail="failure"
56+
)
57+
58+
step_pdp_deactivate = Step(
59+
function=modem_object.deactivate_pdp_context,
60+
name="pdp_deactivate",
61+
success="pdp_activate",
62+
fail="failure"
63+
)
64+
65+
step_pdp_activate = Step(
66+
function=modem_object.activate_pdp_context,
67+
name="pdp_activate",
68+
success="success",
69+
fail="failure",
70+
cachable=True
71+
)
72+
73+
# Create a state for this function to put
74+
# modem's cache.
75+
function_name = "prepare_communication_for_http"
76+
77+
# Create the state manager.
78+
state_manager = StateManager(first_step=step_network_reg,
79+
cache=modem_object.cache,
80+
function_name=function_name)
81+
82+
# Add each step.
83+
state_manager.add_step(step_network_reg)
84+
state_manager.add_step(step_pdp_deactivate)
85+
state_manager.add_step(step_pdp_activate)
86+
87+
# Run the loop to finish state manager.
88+
while True:
89+
result = state_manager.run()
90+
if result["status"] == Status.SUCCESS:
91+
return result
92+
elif result["status"] == Status.ERROR:
93+
return result
94+
time.sleep(result["interval"])
95+
96+
97+
def post_message_to_http_server(modem_object, payload, url=None, query=""):
98+
"""POST request to the HTTP server with a payload and optional query.
99+
100+
Args:
101+
modem_object (Modem): The modem instance to call methods.
102+
payload (dict): The dictionary message which will be sent.
103+
url (str, optional): URL for the host. Defaults to None.
104+
query (str, optional): Query for the server. Defaults to "".
105+
106+
Returns:
107+
dict: A dictionary which has the results inside.
108+
"""
109+
110+
# Set-up the steps for state manager.
111+
step_set_server_url = step_for_setting_server_url(
112+
modem_object, "post_request", url, query)
113+
114+
step_post_request = Step(
115+
function=modem_object.http_post_request,
116+
name="post_request",
117+
success="success",
118+
fail="failure",
119+
function_params={"data": payload},
120+
cachable=True
121+
)
122+
123+
# Create a state for this function to put
124+
# modem's cache.
125+
function_name = "post_message_to_http_server"
126+
127+
# Create the state manager.
128+
state_manager = StateManager(first_step=step_set_server_url,
129+
cache=modem_object.cache,
130+
function_name=function_name)
131+
132+
# Add each step.
133+
state_manager.add_step(step_set_server_url)
134+
state_manager.add_step(step_post_request)
135+
136+
# Run the loop to finish state manager.
137+
while True:
138+
result = state_manager.run()
139+
if result["status"] == Status.SUCCESS:
140+
return result
141+
elif result["status"] == Status.ERROR:
142+
return result
143+
time.sleep(result["interval"])
144+
145+
146+
def get_message_to_http_server(modem_object, url=None, query=""):
147+
"""GET request to the HTTP server with optional query.
148+
149+
Args:
150+
modem_object (Modem): The modem instance to call methods.
151+
url (str, optional): URL for the host. Defaults to None.
152+
query (str, optional): Query for the server. Defaults to "".
153+
154+
Returns:
155+
dict: A dictionary which has the results inside.
156+
"""
157+
158+
# Set-up the steps for state manager.
159+
step_set_server_url = step_for_setting_server_url(
160+
modem_object, "get_request", url, query)
161+
162+
step_get_request = Step(
163+
function=modem_object.http_get_request,
164+
name="get_request",
165+
success="success",
166+
fail="failure",
167+
cachable=True
168+
)
169+
170+
# Create a state for this function to put
171+
# modem's cache.
172+
function_name = "get_message_to_http_server"
173+
174+
# Create the state manager.
175+
state_manager = StateManager(first_step=step_set_server_url,
176+
cache=modem_object.cache,
177+
function_name=function_name)
178+
179+
# Add each step.
180+
state_manager.add_step(step_set_server_url)
181+
state_manager.add_step(step_get_request)
182+
183+
# Run the loop to finish state manager.
184+
while True:
185+
result = state_manager.run()
186+
if result["status"] == Status.SUCCESS:
187+
return result
188+
elif result["status"] == Status.ERROR:
189+
return result
190+
time.sleep(result["interval"])
191+
192+
193+
def put_message_to_http_server(modem_object, payload, url=None, query=""):
194+
"""PUT request to the HTTP server with a payload and optional query.
195+
196+
Args:
197+
modem_object (Modem): The modem instance to call methods.
198+
payload (dict): The dictionary message which will be sent.
199+
url (str, optional): URL for the host. Defaults to None.
200+
query (str, optional): Query for the server. Defaults to "".
201+
202+
Returns:
203+
dict: A dictionary which has the results inside.
204+
"""
205+
206+
# Set-up the steps for state manager.
207+
step_set_server_url = step_for_setting_server_url(
208+
modem_object, "put_request", url, query)
209+
210+
step_put_request = Step(
211+
function=modem_object.http_put_request,
212+
name="put_request",
213+
success="success",
214+
fail="failure",
215+
function_params={"data": payload},
216+
cachable=True
217+
)
218+
219+
# Create a state for this function to put
220+
# modem's cache.
221+
function_name = "put_message_to_http_server"
222+
223+
# Create the state manager.
224+
state_manager = StateManager(first_step=step_set_server_url,
225+
cache=modem_object.cache,
226+
function_name=function_name)
227+
228+
# Add each step.
229+
state_manager.add_step(step_set_server_url)
230+
state_manager.add_step(step_put_request)
231+
232+
# Run the loop to finish state manager.
233+
while True:
234+
result = state_manager.run()
235+
if result["status"] == Status.SUCCESS:
236+
return result
237+
elif result["status"] == Status.ERROR:
238+
return result
239+
time.sleep(result["interval"])
240+
241+
242+
if __name__ == "__main__":
243+
# Initilize the modem object.
244+
modem = Modem({})
245+
# Prepare communication for HTTP.
246+
prepare_communication_for_http(modem)
247+
# Server address to send requests.
248+
HOST = "https://webhook.site/6112efa6-4f8c-4bdb-8fa3-5787cc02f80a"
249+
# Prepare a payload to post into the server.
250+
payload_to_post = {"ProjectTopic": "PicocellHTTPExampleWithManager"}
251+
payload_to_post_as_json = json.dumps(payload_to_post)
252+
# Post it to the server with given query.
253+
post_message_to_http_server(
254+
modem, payload_to_post_as_json, HOST, "device=Pico&try=0")
255+
time.sleep(4)
256+
# Get a request from the server.
257+
get_message_to_http_server(modem, HOST, "company=Sixfab&course=Picocell")
258+
time.sleep(6)
259+
# Prepare a payload to put into the server.
260+
payload_to_put = {"Temperature(*C)": 28}
261+
payload_to_put_as_json = json.dumps(payload_to_put)
262+
# Send the request into the server.
263+
put_message_to_http_server(
264+
modem, payload_to_put_as_json, HOST, "sensor=Garden2")
265+
time.sleep(4)

0 commit comments

Comments
 (0)