Skip to content

Commit 4b846ae

Browse files
Create robot_server.py
Signed-off-by: Fabiana ⚡️ Campanari <113218619+FabianaCampanari@users.noreply.github.com>
1 parent f1abeb8 commit 4b846ae

1 file changed

Lines changed: 154 additions & 0 deletions

File tree

Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
import socket
2+
import threading
3+
import joblib
4+
import pandas as pd
5+
import ast
6+
7+
HOST = '0.0.0.0'
8+
PORT = 5000
9+
10+
model_saved = joblib.load('Bot Status Identificator.pkl')
11+
bot_list = pd.DataFrame(columns=['id', 'conn', 'addr', 'amount_fail'])
12+
bot_list_lock = threading.RLock()
13+
14+
15+
def exist(addr: tuple) -> bool:
16+
'''Verifica se um cliente já existe na lista de bots.'''
17+
global bot_list, bot_list_lock
18+
19+
with bot_list_lock:
20+
if bot_list.empty:
21+
return False
22+
if addr in bot_list['addr'].values:
23+
return True
24+
return False
25+
26+
27+
def register_bot(conn, addr: tuple) -> None:
28+
'''Registra um cliente na lista de bots.'''
29+
global bot_list, bot_list_lock
30+
31+
with bot_list_lock:
32+
if not exist(addr):
33+
bot_list = pd.concat(
34+
[
35+
bot_list,
36+
pd.DataFrame(
37+
{
38+
'id': [len(bot_list) + 1],
39+
'conn': [conn],
40+
'addr': [addr],
41+
'amount_fail': [0]
42+
}
43+
)
44+
],
45+
ignore_index=True
46+
)
47+
48+
49+
def remove_bot(addr: tuple) -> None:
50+
'''Remove um cliente da lista de bots.'''
51+
global bot_list, bot_list_lock
52+
53+
with bot_list_lock:
54+
print(f"Antes: {bot_list.shape[0]} bots")
55+
bot_list = bot_list[bot_list['addr'] != addr].reset_index(drop=True)
56+
print(f"Depois: {bot_list.shape[0]} bots, removido {addr}")
57+
58+
59+
def response(conn, addr: tuple, msg: str) -> None:
60+
'''Envia resposta ao cliente especificado.'''
61+
global bot_list, bot_list_lock
62+
63+
try:
64+
if msg.lower() == 'listar bots':
65+
with bot_list_lock:
66+
msg = str(
67+
[
68+
{'id': row['id'], 'addr': row['addr']}
69+
for _, row in bot_list[['id', 'addr']].iterrows()
70+
]
71+
)
72+
else:
73+
msg_parts = msg.split(',')
74+
with bot_list_lock:
75+
proba = model_saved.predict_proba(
76+
pd.DataFrame(
77+
{
78+
'uptime_horas': ast.literal_eval(msg_parts[0]),
79+
'latencia_ms': ast.literal_eval(msg_parts[1]),
80+
'uso_cpu_pct': ast.literal_eval(msg_parts[2]),
81+
'erros_api_por_minuto': ast.literal_eval(msg_parts[3]),
82+
'versao_firmware': ast.literal_eval(msg_parts[4])
83+
}
84+
)
85+
)
86+
87+
amount_fail = 1
88+
pos_possible_fail = 1
89+
90+
for pos, row in bot_list[['addr', 'amount_fail']].iterrows():
91+
if addr == row['addr']:
92+
amount_fail = row['amount_fail']
93+
pos_possible_fail = pos
94+
break
95+
96+
if proba[0][1] > 0.5:
97+
msg = (
98+
f'1. Status atual do Bot: Funcionamento NORMAL, '
99+
f'com acurácia de {proba[0][1] * 100:.0f}%\n'
100+
f'2. Quantidade de falhas acumuladas: {amount_fail}'
101+
)
102+
else:
103+
bot_list.loc[pos_possible_fail, 'amount_fail'] += 1
104+
msg = (
105+
f'1. Status atual do Bot: FALHA no Funcionamento, '
106+
f'com acurácia de {proba[0][0] * 100:.0f}%\n'
107+
f'2. Quantidade de falhas acumuladas: '
108+
f'{bot_list.loc[pos_possible_fail, "amount_fail"]}'
109+
)
110+
111+
conn.sendall(msg.encode())
112+
113+
except OSError as e:
114+
print(f"Erro ao enviar mensagem para {addr}: {e}")
115+
remove_bot(addr)
116+
117+
118+
def handle_client(conn, addr: tuple):
119+
'''Função para lidar com a conexão do cliente. Recebe o socket da conexão e o endereço do cliente.'''
120+
global bot_list, bot_list_lock
121+
122+
try:
123+
while True:
124+
msg = conn.recv(1024).decode() # Recebe a msg do cliente, decodificando de bytes para string
125+
126+
if msg.lower() == 'sair':
127+
remove_bot(addr)
128+
break # Sai do loop quando o cliente se desconecta
129+
130+
elif msg.lower() == 'cadastro':
131+
register_bot(conn, addr) # Registra o cliente na lista de bots
132+
133+
elif msg:
134+
response(conn, addr, msg) # Envia a mensagem de volta para o cliente
135+
136+
except OSError as e:
137+
# Trata o erro quando o socket é fechado
138+
print(f"Conexão fechada para {addr}: {e}")
139+
remove_bot(addr)
140+
finally:
141+
# Garante que a conexão seja fechada
142+
conn.close()
143+
144+
145+
if __name__ == "__main__":
146+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
147+
server.bind((HOST, PORT))
148+
server.listen(1)
149+
print(f"Servidor ouvindo em {HOST}:{PORT}...")
150+
151+
while True:
152+
conn, addr = server.accept()
153+
print(f"Conexão estabelecida com {addr}")
154+
threading.Thread(target=handle_client, args=(conn, addr)).start()

0 commit comments

Comments
 (0)