-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
83 lines (69 loc) · 2.29 KB
/
main.py
File metadata and controls
83 lines (69 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
from fastapi import FastAPI, HTTPException, Request
from pydantic import BaseModel
from pywifi import PyWiFi, const, Profile
import time
from fastapi.middleware.cors import CORSMiddleware
from fastapi.templating import Jinja2Templates
app = FastAPI()
tpl = Jinja2Templates("public")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class WiFiCredentials(BaseModel):
ssid: str
password: str
@app.get("/")
async def home(r: Request):
return tpl.TemplateResponse("index.html", {"request":r})
def scan_networks():
wifi = PyWiFi()
iface = wifi.interfaces()[0]
iface.scan()
time.sleep(3)
results = iface.scan_results()
networks = []
seen_ssids = set()
for network in results:
if network.ssid and network.ssid not in seen_ssids:
seen_ssids.add(network.ssid)
networks.append(network.ssid)
return networks
def connect_to_network(ssid: str, password: str) -> bool:
wifi = PyWiFi()
iface = wifi.interfaces()[0]
iface.disconnect()
time.sleep(1)
profile = Profile()
profile.ssid = ssid
profile.auth = const.AUTH_ALG_OPEN
profile.akm.append(const.AKM_TYPE_WPA2PSK)
profile.cipher = const.CIPHER_TYPE_CCMP
profile.key = password
iface.remove_all_network_profiles()
tmp_profile = iface.add_network_profile(profile)
iface.connect(tmp_profile)
time.sleep(10)
return iface.status() == const.IFACE_CONNECTED
@app.get("/networks")
def get_networks():
try:
networks = scan_networks()
if not networks:
return {"message": "No se encontraron redes Wi-Fi."}
return {"networks": networks}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/connect")
def connect(credentials: WiFiCredentials):
try:
success = connect_to_network(credentials.ssid, credentials.password)
if success:
return {"message": f"✅ Conectado a '{credentials.ssid}'"}
else:
raise HTTPException(status_code=401, detail="❌ No se pudo conectar.")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))