Update app.py
Browse files
app.py
CHANGED
|
@@ -5,29 +5,35 @@ from datetime import datetime
|
|
| 5 |
import folium
|
| 6 |
from folium import plugins
|
| 7 |
from fastapi import FastAPI, Request
|
|
|
|
| 8 |
import uvicorn
|
| 9 |
from threading import Thread
|
| 10 |
from geopy.distance import geodesic
|
| 11 |
|
| 12 |
-
# Configuração do banco de dados
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
async def receive_location(request: Request):
|
| 19 |
-
data = await request.json()
|
| 20 |
-
device_id = data.get('device_id')
|
| 21 |
-
device_name = data.get('device_name')
|
| 22 |
-
latitude = data.get('latitude')
|
| 23 |
-
longitude = data.get('longitude')
|
| 24 |
-
accuracy = data.get('accuracy', 10)
|
| 25 |
-
battery = data.get('battery', 100)
|
| 26 |
-
|
| 27 |
-
result = add_location(device_id, device_name, latitude, longitude, accuracy, battery)
|
| 28 |
-
return {"status": "success" if "✅" in result else "error", "message": result}
|
| 29 |
|
| 30 |
-
# Função para verificar movimento significativo
|
| 31 |
def is_significant_movement(device_id, new_lat, new_lng):
|
| 32 |
conn = sqlite3.connect('locations.db', check_same_thread=False)
|
| 33 |
cursor = conn.cursor()
|
|
@@ -44,26 +50,133 @@ def is_significant_movement(device_id, new_lat, new_lng):
|
|
| 44 |
|
| 45 |
old_lat, old_lng = last_location
|
| 46 |
distance = geodesic((old_lat, old_lng), (new_lat, new_lng)).meters
|
| 47 |
-
return distance > 50
|
| 48 |
|
| 49 |
-
#
|
| 50 |
def add_location(device_id, device_name, latitude, longitude, accuracy=0, battery=100):
|
| 51 |
try:
|
| 52 |
lat = float(latitude)
|
| 53 |
lng = float(longitude)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
if not is_significant_movement(device_id, lat, lng):
|
| 56 |
return "✅ Localização recebida (sem movimento significativo)"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
-
# Interface Gradio
|
| 62 |
def create_interface():
|
| 63 |
with gr.Blocks(title="📍 Monitor GPS em Tempo Real", theme=gr.themes.Soft()) as demo:
|
| 64 |
gr.Markdown("""
|
| 65 |
# 📍 Monitoramento GPS em Tempo Real
|
| 66 |
-
|
| 67 |
**Visualize a localização de dispositivos com atualização automática**
|
| 68 |
""")
|
| 69 |
|
|
@@ -72,21 +185,19 @@ def create_interface():
|
|
| 72 |
map_html = gr.HTML(label="Mapa GPS em Tempo Real")
|
| 73 |
gr.Markdown("""
|
| 74 |
### Instruções para Celular:
|
| 75 |
-
1. Acesse
|
| 76 |
2. Permita o acesso à localização
|
| 77 |
3. Sua posição será atualizada automaticamente
|
| 78 |
""")
|
| 79 |
-
|
| 80 |
-
# Atualização mais frequente para o mapa
|
| 81 |
gr.Timer(10.0, get_updated_map, [], [map_html])
|
| 82 |
|
| 83 |
with gr.TabItem("📋 Dispositivos"):
|
| 84 |
devices_table = gr.Dataframe(label="Dispositivos Conectados")
|
| 85 |
-
gr.Timer(15.0, get_device_list, [], [devices_table])
|
| 86 |
|
| 87 |
return demo
|
| 88 |
|
| 89 |
-
#
|
| 90 |
mobile_page = """
|
| 91 |
<!DOCTYPE html>
|
| 92 |
<html>
|
|
@@ -95,7 +206,8 @@ mobile_page = """
|
|
| 95 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 96 |
<style>
|
| 97 |
body { font-family: Arial, sans-serif; padding: 20px; }
|
| 98 |
-
button { padding: 10px 15px; font-size: 16px; }
|
|
|
|
| 99 |
</style>
|
| 100 |
</head>
|
| 101 |
<body>
|
|
@@ -106,38 +218,57 @@ mobile_page = """
|
|
| 106 |
|
| 107 |
<script>
|
| 108 |
const deviceId = "celular_" + Math.random().toString(36).substring(2, 8);
|
| 109 |
-
const deviceName =
|
| 110 |
let watchId = null;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
-
document.getElementById("startBtn").addEventListener("click", () => {
|
| 113 |
if (watchId) {
|
| 114 |
navigator.geolocation.clearWatch(watchId);
|
| 115 |
watchId = null;
|
| 116 |
document.getElementById("status").textContent = "Compartilhamento parado";
|
|
|
|
| 117 |
return;
|
| 118 |
}
|
| 119 |
|
| 120 |
document.getElementById("status").textContent = "Obtendo localização...";
|
|
|
|
| 121 |
|
| 122 |
watchId = navigator.geolocation.watchPosition(
|
| 123 |
-
(position) => {
|
| 124 |
const { latitude, longitude, accuracy } = position.coords;
|
| 125 |
-
document.getElementById("coordinates").
|
| 126 |
-
|
|
|
|
|
|
|
| 127 |
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
},
|
| 142 |
(error) => {
|
| 143 |
document.getElementById("status").textContent = "Erro: " + error.message;
|
|
@@ -148,28 +279,50 @@ mobile_page = """
|
|
| 148 |
timeout: 5000
|
| 149 |
}
|
| 150 |
);
|
| 151 |
-
|
| 152 |
-
document.getElementById("status").textContent = "Compartilhando localização...";
|
| 153 |
});
|
| 154 |
</script>
|
| 155 |
</body>
|
| 156 |
</html>
|
| 157 |
"""
|
| 158 |
|
| 159 |
-
# Rota para a página mobile
|
| 160 |
@app.get("/mobile")
|
| 161 |
async def mobile_client():
|
| 162 |
return HTMLResponse(mobile_page)
|
| 163 |
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
|
| 169 |
if __name__ == "__main__":
|
| 170 |
-
|
| 171 |
-
gradio_thread = Thread(target=run_app)
|
| 172 |
gradio_thread.start()
|
| 173 |
|
| 174 |
-
# Iniciar FastAPI
|
| 175 |
uvicorn.run(app, host="0.0.0.0", port=8000)
|
|
|
|
| 5 |
import folium
|
| 6 |
from folium import plugins
|
| 7 |
from fastapi import FastAPI, Request
|
| 8 |
+
from fastapi.responses import HTMLResponse
|
| 9 |
import uvicorn
|
| 10 |
from threading import Thread
|
| 11 |
from geopy.distance import geodesic
|
| 12 |
|
| 13 |
+
# Configuração do banco de dados
|
| 14 |
+
def init_db():
|
| 15 |
+
conn = sqlite3.connect('locations.db', check_same_thread=False)
|
| 16 |
+
cursor = conn.cursor()
|
| 17 |
+
cursor.execute('''
|
| 18 |
+
CREATE TABLE IF NOT EXISTS locations (
|
| 19 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 20 |
+
device_id TEXT NOT NULL,
|
| 21 |
+
device_name TEXT NOT NULL,
|
| 22 |
+
latitude REAL NOT NULL,
|
| 23 |
+
longitude REAL NOT NULL,
|
| 24 |
+
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
| 25 |
+
accuracy REAL,
|
| 26 |
+
battery_level INTEGER,
|
| 27 |
+
ip_address TEXT
|
| 28 |
+
)
|
| 29 |
+
''')
|
| 30 |
+
conn.commit()
|
| 31 |
+
conn.close()
|
| 32 |
|
| 33 |
+
init_db()
|
| 34 |
+
app = FastAPI()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
+
# Função para verificar movimento significativo
|
| 37 |
def is_significant_movement(device_id, new_lat, new_lng):
|
| 38 |
conn = sqlite3.connect('locations.db', check_same_thread=False)
|
| 39 |
cursor = conn.cursor()
|
|
|
|
| 50 |
|
| 51 |
old_lat, old_lng = last_location
|
| 52 |
distance = geodesic((old_lat, old_lng), (new_lat, new_lng)).meters
|
| 53 |
+
return distance > 50
|
| 54 |
|
| 55 |
+
# Função para adicionar localização
|
| 56 |
def add_location(device_id, device_name, latitude, longitude, accuracy=0, battery=100):
|
| 57 |
try:
|
| 58 |
lat = float(latitude)
|
| 59 |
lng = float(longitude)
|
| 60 |
+
acc = float(accuracy) if accuracy else 0
|
| 61 |
+
bat = int(battery) if battery else 100
|
| 62 |
+
|
| 63 |
+
if not (-90 <= lat <= 90) or not (-180 <= lng <= 180):
|
| 64 |
+
return "❌ Erro: Coordenadas inválidas!"
|
| 65 |
|
| 66 |
if not is_significant_movement(device_id, lat, lng):
|
| 67 |
return "✅ Localização recebida (sem movimento significativo)"
|
| 68 |
+
|
| 69 |
+
conn = sqlite3.connect('locations.db', check_same_thread=False)
|
| 70 |
+
cursor = conn.cursor()
|
| 71 |
+
|
| 72 |
+
cursor.execute('''
|
| 73 |
+
INSERT INTO locations (device_id, device_name, latitude, longitude, accuracy, battery_level)
|
| 74 |
+
VALUES (?, ?, ?, ?, ?, ?)
|
| 75 |
+
''', (device_id, device_name, lat, lng, acc, bat))
|
| 76 |
+
|
| 77 |
+
conn.commit()
|
| 78 |
+
conn.close()
|
| 79 |
+
|
| 80 |
+
return f"✅ Localização adicionada com sucesso!\n📍 {lat:.6f}, {lng:.6f}\n⏰ {datetime.now().strftime('%H:%M:%S')}"
|
| 81 |
+
|
| 82 |
+
except ValueError:
|
| 83 |
+
return "❌ Erro: Valores numéricos inválidos!"
|
| 84 |
+
except Exception as e:
|
| 85 |
+
return f"❌ Erro: {str(e)}"
|
| 86 |
+
|
| 87 |
+
# Endpoint API
|
| 88 |
+
@app.post("/api/location")
|
| 89 |
+
async def receive_location(request: Request):
|
| 90 |
+
data = await request.json()
|
| 91 |
+
result = add_location(
|
| 92 |
+
data.get('device_id'),
|
| 93 |
+
data.get('device_name'),
|
| 94 |
+
data.get('latitude'),
|
| 95 |
+
data.get('longitude'),
|
| 96 |
+
data.get('accuracy', 10),
|
| 97 |
+
data.get('battery', 100)
|
| 98 |
+
)
|
| 99 |
+
return {"status": "success" if "✅" in result else "error", "message": result}
|
| 100 |
+
|
| 101 |
+
# Função para obter mapa atualizado
|
| 102 |
+
def get_updated_map():
|
| 103 |
+
try:
|
| 104 |
+
conn = sqlite3.connect('locations.db', check_same_thread=False)
|
| 105 |
+
query = '''
|
| 106 |
+
SELECT device_id, device_name, latitude, longitude,
|
| 107 |
+
timestamp, accuracy, battery_level,
|
| 108 |
+
ROW_NUMBER() OVER (PARTITION BY device_id ORDER BY timestamp DESC) as rn
|
| 109 |
+
FROM locations
|
| 110 |
+
WHERE timestamp > datetime('now', '-1 day')
|
| 111 |
+
'''
|
| 112 |
+
df = pd.read_sql_query(query, conn)
|
| 113 |
+
df_latest = df[df['rn'] == 1].copy()
|
| 114 |
+
conn.close()
|
| 115 |
+
|
| 116 |
+
if df_latest.empty:
|
| 117 |
+
m = folium.Map(location=[-14.235, -51.9253], zoom_start=4)
|
| 118 |
+
folium.Marker(
|
| 119 |
+
[-14.235, -51.9253],
|
| 120 |
+
popup="Nenhum dispositivo encontrado",
|
| 121 |
+
icon=folium.Icon(color='gray', icon='info-sign')
|
| 122 |
+
).add_to(m)
|
| 123 |
+
return m._repr_html_()
|
| 124 |
+
|
| 125 |
+
center_lat = df_latest['latitude'].mean()
|
| 126 |
+
center_lng = df_latest['longitude'].mean()
|
| 127 |
+
m = folium.Map(location=[center_lat, center_lng], zoom_start=12)
|
| 128 |
+
|
| 129 |
+
colors = ['red', 'blue', 'green', 'purple', 'orange', 'darkred', 'lightred',
|
| 130 |
+
'beige', 'darkblue', 'darkgreen', 'cadetblue', 'darkpurple', 'white',
|
| 131 |
+
'pink', 'lightblue', 'lightgreen', 'gray', 'black', 'lightgray']
|
| 132 |
+
|
| 133 |
+
for idx, row in df_latest.iterrows():
|
| 134 |
+
last_update = datetime.strptime(row['timestamp'], '%Y-%m-%d %H:%M:%S')
|
| 135 |
+
is_online = (datetime.now() - last_update).total_seconds() < 300
|
| 136 |
+
|
| 137 |
+
popup_html = f"""
|
| 138 |
+
<div style="font-family: Arial; width: 200px;">
|
| 139 |
+
<h4>📱 {row['device_name']}</h4>
|
| 140 |
+
<p><b>ID:</b> {row['device_id']}</p>
|
| 141 |
+
<p><b>Status:</b> <span style="color: {'green' if is_online else 'red'};">
|
| 142 |
+
{'🟢 Online' if is_online else '🔴 Offline'}</span></p>
|
| 143 |
+
<p><b>Última atualização:</b><br>{row['timestamp']}</p>
|
| 144 |
+
<p><b>Coordenadas:</b><br>{row['latitude']:.6f}, {row['longitude']:.6f}</p>
|
| 145 |
+
<p><b>Precisão:</b> ±{row['accuracy']:.0f}m</p>
|
| 146 |
+
<p><b>Bateria:</b> 🔋 {row['battery_level']}%</p>
|
| 147 |
+
</div>
|
| 148 |
+
"""
|
| 149 |
|
| 150 |
+
folium.Marker(
|
| 151 |
+
[row['latitude'], row['longitude']],
|
| 152 |
+
popup=folium.Popup(popup_html, min_width=200, max_width=300),
|
| 153 |
+
tooltip=f"{row['device_name']} - {'Online' if is_online else 'Offline'}",
|
| 154 |
+
icon=folium.Icon(color='green' if is_online else 'red', icon='phone', prefix='fa')
|
| 155 |
+
).add_to(m)
|
| 156 |
+
|
| 157 |
+
folium.Circle(
|
| 158 |
+
[row['latitude'], row['longitude']],
|
| 159 |
+
radius=row['accuracy'],
|
| 160 |
+
popup=f"Área de precisão: ±{row['accuracy']:.0f}m",
|
| 161 |
+
color=colors[idx % len(colors)],
|
| 162 |
+
fill=True,
|
| 163 |
+
fillOpacity=0.1,
|
| 164 |
+
weight=1
|
| 165 |
+
).add_to(m)
|
| 166 |
+
|
| 167 |
+
plugins.Fullscreen().add_to(m)
|
| 168 |
+
minimap = plugins.MiniMap()
|
| 169 |
+
m.add_child(minimap)
|
| 170 |
+
|
| 171 |
+
return m._repr_html_()
|
| 172 |
+
except Exception as e:
|
| 173 |
+
return f"<div style='color: red; padding: 20px;'>Erro ao carregar mapa: {str(e)}</div>"
|
| 174 |
|
| 175 |
+
# Interface Gradio
|
| 176 |
def create_interface():
|
| 177 |
with gr.Blocks(title="📍 Monitor GPS em Tempo Real", theme=gr.themes.Soft()) as demo:
|
| 178 |
gr.Markdown("""
|
| 179 |
# 📍 Monitoramento GPS em Tempo Real
|
|
|
|
| 180 |
**Visualize a localização de dispositivos com atualização automática**
|
| 181 |
""")
|
| 182 |
|
|
|
|
| 185 |
map_html = gr.HTML(label="Mapa GPS em Tempo Real")
|
| 186 |
gr.Markdown("""
|
| 187 |
### Instruções para Celular:
|
| 188 |
+
1. Acesse: http://[SEU-SERVIDOR]:8000/mobile
|
| 189 |
2. Permita o acesso à localização
|
| 190 |
3. Sua posição será atualizada automaticamente
|
| 191 |
""")
|
|
|
|
|
|
|
| 192 |
gr.Timer(10.0, get_updated_map, [], [map_html])
|
| 193 |
|
| 194 |
with gr.TabItem("📋 Dispositivos"):
|
| 195 |
devices_table = gr.Dataframe(label="Dispositivos Conectados")
|
| 196 |
+
gr.Timer(15.0, lambda: get_device_list(), [], [devices_table])
|
| 197 |
|
| 198 |
return demo
|
| 199 |
|
| 200 |
+
# Página mobile
|
| 201 |
mobile_page = """
|
| 202 |
<!DOCTYPE html>
|
| 203 |
<html>
|
|
|
|
| 206 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 207 |
<style>
|
| 208 |
body { font-family: Arial, sans-serif; padding: 20px; }
|
| 209 |
+
button { padding: 10px 15px; font-size: 16px; margin: 10px 0; }
|
| 210 |
+
#status { margin: 15px 0; font-weight: bold; }
|
| 211 |
</style>
|
| 212 |
</head>
|
| 213 |
<body>
|
|
|
|
| 218 |
|
| 219 |
<script>
|
| 220 |
const deviceId = "celular_" + Math.random().toString(36).substring(2, 8);
|
| 221 |
+
const deviceName = prompt("Digite seu nome:", "Usuário") || "Usuário";
|
| 222 |
let watchId = null;
|
| 223 |
+
let batteryLevel = 100;
|
| 224 |
+
|
| 225 |
+
// Verificar suporte a bateria
|
| 226 |
+
if (navigator.getBattery) {
|
| 227 |
+
navigator.getBattery().then(battery => {
|
| 228 |
+
batteryLevel = Math.round(battery.level * 100);
|
| 229 |
+
battery.addEventListener('levelchange', () => {
|
| 230 |
+
batteryLevel = Math.round(battery.level * 100);
|
| 231 |
+
});
|
| 232 |
+
});
|
| 233 |
+
}
|
| 234 |
|
| 235 |
+
document.getElementById("startBtn").addEventListener("click", async () => {
|
| 236 |
if (watchId) {
|
| 237 |
navigator.geolocation.clearWatch(watchId);
|
| 238 |
watchId = null;
|
| 239 |
document.getElementById("status").textContent = "Compartilhamento parado";
|
| 240 |
+
document.getElementById("startBtn").textContent = "Iniciar Compartilhamento";
|
| 241 |
return;
|
| 242 |
}
|
| 243 |
|
| 244 |
document.getElementById("status").textContent = "Obtendo localização...";
|
| 245 |
+
document.getElementById("startBtn").textContent = "Parar Compartilhamento";
|
| 246 |
|
| 247 |
watchId = navigator.geolocation.watchPosition(
|
| 248 |
+
async (position) => {
|
| 249 |
const { latitude, longitude, accuracy } = position.coords;
|
| 250 |
+
document.getElementById("coordinates").innerHTML =
|
| 251 |
+
`<strong>Coordenadas:</strong> ${latitude.toFixed(6)}, ${longitude.toFixed(6)}<br>
|
| 252 |
+
<strong>Precisão:</strong> ${Math.round(accuracy)} metros<br>
|
| 253 |
+
<strong>Bateria:</strong> ${batteryLevel}%`;
|
| 254 |
|
| 255 |
+
try {
|
| 256 |
+
const response = await fetch("/api/location", {
|
| 257 |
+
method: "POST",
|
| 258 |
+
headers: { "Content-Type": "application/json" },
|
| 259 |
+
body: JSON.stringify({
|
| 260 |
+
device_id: deviceId,
|
| 261 |
+
device_name: deviceName,
|
| 262 |
+
latitude,
|
| 263 |
+
longitude,
|
| 264 |
+
accuracy,
|
| 265 |
+
battery: batteryLevel
|
| 266 |
+
})
|
| 267 |
+
});
|
| 268 |
+
console.log("Localização enviada:", await response.json());
|
| 269 |
+
} catch (error) {
|
| 270 |
+
console.error("Erro ao enviar localização:", error);
|
| 271 |
+
}
|
| 272 |
},
|
| 273 |
(error) => {
|
| 274 |
document.getElementById("status").textContent = "Erro: " + error.message;
|
|
|
|
| 279 |
timeout: 5000
|
| 280 |
}
|
| 281 |
);
|
|
|
|
|
|
|
| 282 |
});
|
| 283 |
</script>
|
| 284 |
</body>
|
| 285 |
</html>
|
| 286 |
"""
|
| 287 |
|
|
|
|
| 288 |
@app.get("/mobile")
|
| 289 |
async def mobile_client():
|
| 290 |
return HTMLResponse(mobile_page)
|
| 291 |
|
| 292 |
+
def get_device_list():
|
| 293 |
+
try:
|
| 294 |
+
conn = sqlite3.connect('locations.db', check_same_thread=False)
|
| 295 |
+
query = '''
|
| 296 |
+
SELECT device_id, device_name, latitude, longitude,
|
| 297 |
+
timestamp, battery_level, accuracy,
|
| 298 |
+
ROW_NUMBER() OVER (PARTITION BY device_id ORDER BY timestamp DESC) as rn
|
| 299 |
+
FROM locations
|
| 300 |
+
WHERE timestamp > datetime('now', '-1 day')
|
| 301 |
+
'''
|
| 302 |
+
df = pd.read_sql_query(query, conn)
|
| 303 |
+
conn.close()
|
| 304 |
+
|
| 305 |
+
if df.empty:
|
| 306 |
+
return pd.DataFrame([{"Mensagem": "Nenhum dispositivo encontrado nas últimas 24 horas"}])
|
| 307 |
+
|
| 308 |
+
df_latest = df[df['rn'] == 1].copy()
|
| 309 |
+
df_latest['status'] = df_latest['timestamp'].apply(
|
| 310 |
+
lambda x: '🟢 Online' if (datetime.now() - datetime.strptime(x, '%Y-%m-%d %H:%M:%S')).total_seconds() < 300 else '🔴 Offline'
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
display_df = df_latest[['device_name', 'device_id', 'status', 'latitude', 'longitude', 'timestamp', 'battery_level', 'accuracy']]
|
| 314 |
+
display_df.columns = ['Nome', 'ID', 'Status', 'Latitude', 'Longitude', 'Última Atualização', 'Bateria (%)', 'Precisão (m)']
|
| 315 |
+
|
| 316 |
+
return display_df
|
| 317 |
+
except Exception as e:
|
| 318 |
+
return pd.DataFrame([{"Erro": f"Erro ao carregar dispositivos: {str(e)}"}])
|
| 319 |
+
|
| 320 |
+
def run_gradio():
|
| 321 |
+
demo = create_interface()
|
| 322 |
+
demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
|
| 323 |
|
| 324 |
if __name__ == "__main__":
|
| 325 |
+
gradio_thread = Thread(target=run_gradio)
|
|
|
|
| 326 |
gradio_thread.start()
|
| 327 |
|
|
|
|
| 328 |
uvicorn.run(app, host="0.0.0.0", port=8000)
|