Add Raspberry Pi Pico project
This commit is contained in:
84
pico/wifi_client.py
Normal file
84
pico/wifi_client.py
Normal file
@@ -0,0 +1,84 @@
|
||||
import network
|
||||
import urequests
|
||||
import time
|
||||
import usocket
|
||||
import socket
|
||||
import ssl
|
||||
|
||||
# global variable for the IP-Adress of the laptop hotspot
|
||||
IP_ADRESS_SERVER:str = '192.168.0.100' #None
|
||||
IP_ADRESS_ACCESSPOINT = None
|
||||
SERVER_PORT:int = 3000 #None
|
||||
|
||||
# configures the raspberry pi as wifi-client and connects it to an access point
|
||||
def wifi_connect(SSID:str, PASSWORD:str) -> None:
|
||||
|
||||
# configure raspberry pi as client
|
||||
wifi = network.WLAN(network.STA_IF)
|
||||
# activate client
|
||||
wifi.active(True)
|
||||
# connect to laptop hotspot
|
||||
wifi.connect(SSID, PASSWORD)
|
||||
|
||||
# wait until it has connected
|
||||
while not wifi.isconnected():
|
||||
print("Connect to", SSID, "...")
|
||||
time.sleep(1)
|
||||
|
||||
# connected to laptop hotspot
|
||||
print("Connected to", SSID)
|
||||
# geat and print IP-adress of raspberry
|
||||
ip_adress_pico = wifi.ifconfig()[0]
|
||||
print("IP-Adresse Pico:", ip_adress_pico)
|
||||
# get ip-adress of access point and store it in the global variable
|
||||
global IP_ADRESS_ACCESSPOINT
|
||||
IP_ADRESS_ACCESSPOINT = wifi.ifconfig()[2]
|
||||
print("IP-adress access point:", IP_ADRESS_ACCESSPOINT)
|
||||
print()
|
||||
|
||||
|
||||
|
||||
# send a HTTP-request to the access point with the rate value
|
||||
def send_request(rate_value:int) -> None:
|
||||
|
||||
# create HTTP-URL
|
||||
URL = f"http://{IP_ADRESS_SERVER}:{str(SERVER_PORT)}/rating/{rate_value}"
|
||||
print(URL)
|
||||
|
||||
# create request
|
||||
response = urequests.get(URL)
|
||||
|
||||
# print HTTP-answer of the access point
|
||||
print("Server response:")
|
||||
print(response.text) # Die Antwort des Servers anzeigen
|
||||
print()
|
||||
response.close()
|
||||
|
||||
|
||||
# test, if there can be a connection to the given ip adress and port
|
||||
def ping_ip(ip:str, port:int) -> bool:
|
||||
s = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
|
||||
s.settimeout(1)
|
||||
try:
|
||||
s.connect((ip, port))
|
||||
print(f"{ip} reachable")
|
||||
s.close()
|
||||
return True
|
||||
except:
|
||||
print(f"{ip} not reachable")
|
||||
s.close()
|
||||
return False
|
||||
|
||||
|
||||
# search for the server in the lokal network
|
||||
# in the ip range from lower_limit to upper_limit
|
||||
def search_server(lower_limit:int, upper_limit:int, port:int) -> str:
|
||||
global IP_ADRESS_SERVER
|
||||
for i in range(lower_limit, upper_limit):
|
||||
ip = IP_ADRESS_ACCESSPOINT[:-1] + str(i)
|
||||
if ping_ip(ip, port):
|
||||
print(f"Server found unter: {ip}:{port}")
|
||||
IP_ADRESS_SERVER = ip
|
||||
return ip
|
||||
|
||||
|
Reference in New Issue
Block a user