-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
108 lines (89 loc) · 3.05 KB
/
main.py
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
from dotenv import load_dotenv
from os import getenv
import sys
from typing import Tuple, List
import time
from time import sleep
import requests as req
from requests import Response, ConnectionError
import bluetooth # only supported on Linux
load_dotenv()
server = getenv("SERVER_URL")
token = getenv("TOKEN")
def wait(secs: int, error: str = ""):
error = error + " " if error and not error.endswith(" ") else error
for s in range(secs - 1):
print(error +
f"Resuming in {str(secs - s).zfill(len(str(secs)))} seconds...",
end="\r")
sys.stdout.write('\033[2K\033[1G')
sleep(1)
print(error + f"Resuming in {secs} seconds.")
def handleNearby(nearby: List[Tuple[str, str, int]]):
month, day, hour, minutes, sec = time.strftime("%m %d %H %M %S").split()
text = f"Found {len(nearby)} devices on the {day}/{month} at {hour}:{minutes}:{sec}"
print("- " + text, end="\r")
sys.stdout.write('\033[2K\033[1G')
devices = list(
map(lambda n: ({
"address": n[0],
"name": n[1],
"type": n[2]
}), nearby))
try:
res = req.post(f"{server}/ping",
json={"devices": devices},
headers={"Authorization": token})
handleReponse(res, text)
except ConnectionError as e:
print("X " + text)
wait(60, " Failed to reach server.")
def handleReponse(res: Response, text: str):
status = res.status_code
success = str(status).startswith("2")
if success:
print("| " + text)
else:
print("X " + text)
if str(status).startswith("4"):
if status == 422:
print(" ERR 422 | Sent invalid data.")
elif status == 401:
print(" ERR 401 | Cannot authenticate.")
else:
print(f" ERR {status} | Unknown error. Response body:")
print(" " + res.text)
elif str(status).startswith("5"):
print(f" ERR {status} | Server error. Response body:")
print(" " + res.text)
wait(60)
def getIdentity():
found = False
while not found:
try:
res = req.get(f"{server}/self", headers={"Authorization": token})
found = True
json = res.json()
if res.status_code != 200:
print("Authentication failed. Terminating.")
wait(60)
return json
except ConnectionError:
wait(60, "Failed to initiate connection with server.")
def main():
print("Starting...")
id = getIdentity()
print(f"Emitting as \"{id['name']}\" [{id['id']}].\n")
while True:
print("* " + "Searching...", end="\r")
sys.stdout.write('\033[2K\033[1G')
nearby: List[Tuple[str, str, int]] = bluetooth.discover_devices(
duration=8, lookup_names=True, lookup_class=True)
handleNearby(nearby)
try:
if __name__ == "__main__":
main()
else:
print("Script should be main")
except KeyboardInterrupt:
exit()