ultimas correcoes
This commit is contained in:
parent
38b712b375
commit
d64c49f3cc
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -1,4 +1,5 @@
|
||||||
using AgroBase.Services;
|
using AgroBase.Models;
|
||||||
|
using AgroBase.Services;
|
||||||
using CefSharp;
|
using CefSharp;
|
||||||
using CefSharp.WinForms;
|
using CefSharp.WinForms;
|
||||||
using System;
|
using System;
|
||||||
|
|
@ -8,13 +9,16 @@ namespace AgroBase.Forms
|
||||||
{
|
{
|
||||||
public partial class frmGPS : Form
|
public partial class frmGPS : Form
|
||||||
{
|
{
|
||||||
private ChromiumWebBrowser chromiumWebBrowser;
|
private MapasModel Mapa;
|
||||||
private MapasService mapaService = new MapasService();
|
|
||||||
Timer tmrUpdate = new Timer();
|
|
||||||
|
|
||||||
public frmGPS()
|
public frmGPS()
|
||||||
{
|
{
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
|
|
||||||
|
Mapa = new MapasModel()
|
||||||
|
{
|
||||||
|
pnlMapa = pnlMapa,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private void frmGPS_Load(object sender, EventArgs e)
|
private void frmGPS_Load(object sender, EventArgs e)
|
||||||
|
|
@ -24,58 +28,12 @@ namespace AgroBase.Forms
|
||||||
|
|
||||||
private void frmGPS_FormClosing(object sender, FormClosingEventArgs e)
|
private void frmGPS_FormClosing(object sender, FormClosingEventArgs e)
|
||||||
{
|
{
|
||||||
try
|
Mapa.PararProcessamento();
|
||||||
{
|
|
||||||
GPSService.PararRecepcaoDados();
|
|
||||||
|
|
||||||
tmrUpdate.Stop();
|
|
||||||
mapaService.pythonProcess.Kill();
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
Console.WriteLine(ex.Message);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void IniciarMapa()
|
private void IniciarMapa()
|
||||||
{
|
{
|
||||||
GPSService.IniciarRecepcaoDados();
|
Mapa.CarregarMapaGPS();
|
||||||
|
|
||||||
mapaService.CarregarMapaGPS(MapasVariaveisModel.NomeArquivoMapaGPS);
|
|
||||||
picLoading.Visible = true;
|
|
||||||
tmrUpdate = new Timer() { Interval = 1000 };
|
|
||||||
tmrUpdate.Tick -= Tmr_Tick;
|
|
||||||
tmrUpdate.Tick += Tmr_Tick;
|
|
||||||
tmrUpdate.Start();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void Tmr_Tick(object sender, EventArgs e)
|
|
||||||
{
|
|
||||||
if (picLoading.Visible)
|
|
||||||
{
|
|
||||||
picLoading.Visible = false;
|
|
||||||
|
|
||||||
chromiumWebBrowser = new ChromiumWebBrowser(mapaService.MapaUrl);
|
|
||||||
this.pnlMapa.Controls.Add(chromiumWebBrowser);
|
|
||||||
chromiumWebBrowser.Dock = DockStyle.Fill;
|
|
||||||
|
|
||||||
//InjectJavaScriptFunctionsAsync();
|
|
||||||
|
|
||||||
//tmrUpdate.Stop();
|
|
||||||
}
|
|
||||||
else if (!picLoading.Visible && GPSService.UltimaLeitura != null)
|
|
||||||
{
|
|
||||||
mapaService.AtualizarPosicaoMapaGPS(GPSService.UltimaLeitura.Latitude, GPSService.UltimaLeitura.Longitude);
|
|
||||||
chromiumWebBrowser.Reload();
|
|
||||||
|
|
||||||
lblDatahora.Text = "Ultima Leitura: " + GPSService.UltimaLeitura.DataHora.ToString("dd/MM/yyyy HH:mm:ss");
|
|
||||||
lblLatitude.Text = "Latitude: " + GPSService.UltimaLeitura.Latitude;
|
|
||||||
lblLongitude.Text = "Longitude: " + GPSService.UltimaLeitura.Longitude;
|
|
||||||
lblPrecisao.Text = "Precisão: " + GPSService.UltimaLeitura.PrecisaoHorizontal;
|
|
||||||
lblSatelites.Text = "Satelites: " + GPSService.UltimaLeitura.NumeroSatelites;
|
|
||||||
lblVelocidade.Text = "Velocidade: " + GPSService.UltimaLeitura.Velocidade;
|
|
||||||
lblAltitude.Text = "Altitude: " + GPSService.UltimaLeitura.Altitude;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -251,6 +251,7 @@ namespace AgroBase
|
||||||
bool MovConectado = Variaveis.DispositivosConectados.Any(x => x.Dispositivo == T_Code.Mov && (x._Porta.IsOpen || DebugMode));
|
bool MovConectado = Variaveis.DispositivosConectados.Any(x => x.Dispositivo == T_Code.Mov && (x._Porta.IsOpen || DebugMode));
|
||||||
bool DirConectado = Variaveis.DispositivosConectados.Any(x => x.Dispositivo == T_Code.Dir && (x._Porta.IsOpen || DebugMode));
|
bool DirConectado = Variaveis.DispositivosConectados.Any(x => x.Dispositivo == T_Code.Dir && (x._Porta.IsOpen || DebugMode));
|
||||||
bool AtuConectado = Variaveis.DispositivosConectados.Any(x => x.Dispositivo == T_Code.Atu && (x._Porta.IsOpen || DebugMode));
|
bool AtuConectado = Variaveis.DispositivosConectados.Any(x => x.Dispositivo == T_Code.Atu && (x._Porta.IsOpen || DebugMode));
|
||||||
|
bool GpsConectado = GPSService.PortaGPS != null;
|
||||||
|
|
||||||
if (Variaveis.OperacaoEmAndamento.Iniciado)
|
if (Variaveis.OperacaoEmAndamento.Iniciado)
|
||||||
{
|
{
|
||||||
|
|
@ -295,6 +296,20 @@ namespace AgroBase
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
else if (Variaveis.OperacaoEmAndamento.Modo == ModoOperacao.MapaGPS)
|
||||||
|
{
|
||||||
|
if (GpsConectado)
|
||||||
|
{
|
||||||
|
frmGPS frmGPS = new frmGPS();
|
||||||
|
frmGPS.Show();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
MensagemErro = "Para iniciar a operação " + Enum.GetName(typeof(ModoOperacao), Variaveis.OperacaoEmAndamento.Modo) +
|
||||||
|
", é necessário que os seguintes módulos estejam devidamente conectados ao equipamento:\r\n" +
|
||||||
|
"GPS: ( " + (GpsConectado ? "OK" : " ") + " )";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (MensagemErro != "")
|
if (MensagemErro != "")
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -35,6 +35,14 @@ namespace AgroBase.Models
|
||||||
tmr.Start();
|
tmr.Start();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void CarregarMapaGPS()
|
||||||
|
{
|
||||||
|
mapaService.CarregarMapaGPS(MapasVariaveisModel.NomeArquivoMapaGPS);
|
||||||
|
Timer tmr = new Timer() { Interval = 500 };
|
||||||
|
tmr.Tick += Tmr_Tick;
|
||||||
|
tmr.Start();
|
||||||
|
}
|
||||||
|
|
||||||
private void Tmr_Tick(object sender, EventArgs e)
|
private void Tmr_Tick(object sender, EventArgs e)
|
||||||
{
|
{
|
||||||
if (mapaService.pythonProcess.HasExited)
|
if (mapaService.pythonProcess.HasExited)
|
||||||
|
|
@ -42,14 +50,31 @@ namespace AgroBase.Models
|
||||||
((Timer)sender).Stop();
|
((Timer)sender).Stop();
|
||||||
picLoading.Visible = false;
|
picLoading.Visible = false;
|
||||||
|
|
||||||
mapaService.CarregarDadosMapa();
|
if (mapaService.NomeArquivoMapa == MapasVariaveisModel.NomeArquivoMapaInterativo)
|
||||||
|
{
|
||||||
|
mapaService.CarregarDadosMapa();
|
||||||
|
lblMapa.Text = "Mapa carregado: " + mapaService.NomeArquivos;
|
||||||
|
}
|
||||||
|
|
||||||
lblMapa.Text = "Mapa carregado: " + mapaService.NomeArquivos;
|
IniciarProcessamento();
|
||||||
chromiumWebBrowser = new ChromiumWebBrowser(mapaService.MapaUrl);
|
|
||||||
pnlMapa.Controls.Add(chromiumWebBrowser);
|
|
||||||
chromiumWebBrowser.Dock = DockStyle.Fill;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void IniciarProcessamento()
|
||||||
|
{
|
||||||
|
APIService.Inicializar();
|
||||||
|
GPSService.IniciarRecepcaoDados();
|
||||||
|
|
||||||
|
chromiumWebBrowser = new ChromiumWebBrowser(mapaService.MapaUrl);
|
||||||
|
pnlMapa.Controls.Add(chromiumWebBrowser);
|
||||||
|
chromiumWebBrowser.Dock = DockStyle.Fill;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void PararProcessamento()
|
||||||
|
{
|
||||||
|
APIService.Parar();
|
||||||
|
GPSService.PararRecepcaoDados();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public class MapaFeatureCollectionModel
|
public class MapaFeatureCollectionModel
|
||||||
|
|
|
||||||
|
|
@ -1,40 +1,152 @@
|
||||||
from flask import Flask, jsonify, request
|
import geopandas as gpd
|
||||||
import folium
|
import json
|
||||||
import sys
|
import sys
|
||||||
|
import folium
|
||||||
|
import requests
|
||||||
|
import re
|
||||||
|
|
||||||
app = Flask(__name__)
|
def internet_disponivel():
|
||||||
|
"""Verifica se há conexão com a internet."""
|
||||||
|
url = 'http://www.google.com/'
|
||||||
|
timeout = 5
|
||||||
|
try:
|
||||||
|
_ = requests.get(url, timeout=timeout)
|
||||||
|
return True
|
||||||
|
except requests.ConnectionError:
|
||||||
|
return False
|
||||||
|
|
||||||
# Armazena a última localização conhecida
|
# Argumentos e configurações iniciais
|
||||||
last_known_location = (-22.1839247, -47.3824123)
|
pathFiles = sys.argv[1]
|
||||||
|
fileName = sys.argv[2]
|
||||||
|
outputName = sys.argv[3]
|
||||||
|
outputMapName = sys.argv[4]
|
||||||
|
apiEndpoit = sys.argv[5]
|
||||||
|
pastaSaida = 'Python/Output/'
|
||||||
|
|
||||||
# Rota para renderizar o mapa inicial
|
center = [0, 0]
|
||||||
@app.route('/')
|
|
||||||
def index():
|
|
||||||
global last_known_location
|
|
||||||
folium_map = folium.Map(location=last_known_location, zoom_start=20)
|
|
||||||
folium.Marker(last_known_location, tooltip='Ponto GPS').add_to(folium_map)
|
|
||||||
return folium_map._repr_html_()
|
|
||||||
|
|
||||||
# Rota para atualizar as coordenadas do marcador
|
# Verificar se há conexão com a internet
|
||||||
@app.route('/update_marker', methods=['POST'])
|
if internet_disponivel():
|
||||||
def update_marker():
|
m = folium.Map(location=center, zoom_start=12)
|
||||||
global last_known_location
|
else:
|
||||||
data = request.json
|
m = folium.Map(location=center, zoom_start=12, tiles=None)
|
||||||
last_known_location = (data['lat'], data['lon'])
|
|
||||||
return jsonify({'message': 'Coordenadas atualizadas com sucesso!'}), 200
|
|
||||||
|
|
||||||
# Rota para obter as coordenadas do marcador
|
# Salvar o mapa interativo em um arquivo HTML
|
||||||
@app.route('/get_marker')
|
m.save(pastaSaida + outputMapName)
|
||||||
def get_marker():
|
|
||||||
global last_known_location
|
|
||||||
return jsonify(last_known_location)
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
port = 5000 # Porta padrão
|
# Caminho completo para o arquivo HTML gerado
|
||||||
if len(sys.argv) > 1:
|
caminho_completo_html = pastaSaida + outputMapName
|
||||||
try:
|
|
||||||
port = int(sys.argv[1])
|
# Abrir o arquivo HTML para leitura e escrita
|
||||||
except ValueError:
|
with open(caminho_completo_html, 'r+') as arquivo_html:
|
||||||
print("Por favor forneça um número de porta válido.")
|
# Ler o conteúdo do arquivo
|
||||||
sys.exit(1)
|
conteudo_html = arquivo_html.read()
|
||||||
app.run(debug=True, port=port)
|
|
||||||
|
# Usar expressão regular para encontrar o ID do mapa
|
||||||
|
padrao_id_mapa = re.compile(r'id="map_(.*?)"')
|
||||||
|
resultado_busca = padrao_id_mapa.search(conteudo_html)
|
||||||
|
|
||||||
|
# Verificar se encontrou um ID de mapa
|
||||||
|
if resultado_busca:
|
||||||
|
id_mapa = 'map_' + resultado_busca.group(1)
|
||||||
|
else:
|
||||||
|
raise ValueError("Não foi possível encontrar o ID do mapa no arquivo HTML.")
|
||||||
|
|
||||||
|
# Script JavaScript para adicionar ao HTML, com o ID do mapa substituído
|
||||||
|
script_atualizacao_marcador = f"""
|
||||||
|
<script>
|
||||||
|
function trajeto_json_onEachFeature(feature, layer) {{
|
||||||
|
layer.on({{
|
||||||
|
}});
|
||||||
|
}};
|
||||||
|
var trajeto_json = L.geoJson(null, {{
|
||||||
|
onEachFeature: trajeto_json_onEachFeature,
|
||||||
|
style: function(feature) {{
|
||||||
|
return {{color: 'red'}};
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
);
|
||||||
|
function trajeto_json_add (data) {{
|
||||||
|
trajeto_json.addData(data);
|
||||||
|
}}
|
||||||
|
trajeto_json_add({{"features": []}});
|
||||||
|
|
||||||
|
trajeto_json.addTo({id_mapa});
|
||||||
|
|
||||||
|
function adicionarGeometria(novaGeometria) {{
|
||||||
|
trajeto_json.addData(novaGeometria);
|
||||||
|
}}
|
||||||
|
|
||||||
|
function saoCoordenadasIguais(coord1, coord2, tolerancia) {{
|
||||||
|
return Math.abs(coord1[0] - coord2[0]) < tolerancia && Math.abs(coord1[1] - coord2[1]) < tolerancia;
|
||||||
|
}}
|
||||||
|
|
||||||
|
function adicionarCoordenada(idGeometria, novaCoordenada) {{
|
||||||
|
var feature = trajeto_json.toGeoJSON().features.find(f => f.id === idGeometria);
|
||||||
|
if (feature) {{
|
||||||
|
var ultima = [0.0,0.0];
|
||||||
|
if (feature.geometry.coordinates.length > 0) {{
|
||||||
|
ultima = feature.geometry.coordinates[feature.geometry.coordinates.length - 1];
|
||||||
|
}}
|
||||||
|
if (!saoCoordenadasIguais(ultima, novaCoordenada, 0.000001)) {{
|
||||||
|
feature.geometry.coordinates.push(novaCoordenada);
|
||||||
|
var ft = feature;
|
||||||
|
trajeto_json.clearLayers();
|
||||||
|
trajeto_json.addData(ft);
|
||||||
|
}}
|
||||||
|
|
||||||
|
}} else {{
|
||||||
|
console.log("Feature com ID " + idGeometria + " não encontrada.");
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
|
||||||
|
adicionarGeometria({{
|
||||||
|
"type": "Feature",
|
||||||
|
"geometry": {{
|
||||||
|
"type": "LineString",
|
||||||
|
"coordinates": []
|
||||||
|
}},
|
||||||
|
"properties": {{"Dist1": 0.0, "Dist2": 0.0, "Id": 1517, "Length": 21.724783283, "Name": "Projeto"}},
|
||||||
|
"id": "Tj"
|
||||||
|
}});
|
||||||
|
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
var marcadorDinamico = L.marker([0, 0], {{
|
||||||
|
icon: L.AwesomeMarkers.icon({{
|
||||||
|
icon: 'info-sign',
|
||||||
|
markerColor: 'red',
|
||||||
|
prefix: 'glyphicon'
|
||||||
|
}})
|
||||||
|
}}).addTo({id_mapa});
|
||||||
|
|
||||||
|
function atualizarMarcador() {{
|
||||||
|
fetch('{apiEndpoit}')
|
||||||
|
.then(function(response) {{
|
||||||
|
return response.json();
|
||||||
|
}})
|
||||||
|
.then(function(dados) {{
|
||||||
|
var novaLatitude = dados.latitude;
|
||||||
|
var novaLongitude = dados.longitude;
|
||||||
|
var novaPosicao = [novaLatitude, novaLongitude];
|
||||||
|
marcadorDinamico.setLatLng(novaPosicao);
|
||||||
|
adicionarCoordenada("Tj", [novaLongitude, novaLatitude]);
|
||||||
|
}})
|
||||||
|
.catch(function(error) {{
|
||||||
|
console.error('Erro ao atualizar o marcador:', error);
|
||||||
|
}});
|
||||||
|
}}
|
||||||
|
|
||||||
|
// Atualiza o marcador a cada 2 segundos
|
||||||
|
setInterval(atualizarMarcador, 2000);
|
||||||
|
</script>
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Inserir o script no conteúdo HTML
|
||||||
|
conteudo_atualizado = conteudo_html.replace('</html>', script_atualizacao_marcador + '</html>')
|
||||||
|
|
||||||
|
# Agora, reabrir o arquivo para escrita e sobrescrever o conteúdo com a versão atualizada
|
||||||
|
with open(caminho_completo_html, 'w') as arquivo_html:
|
||||||
|
arquivo_html.write(conteudo_atualizado)
|
||||||
|
|
@ -21,7 +21,7 @@ namespace AgroBase.Services
|
||||||
OpenFileDialog opfMapa;
|
OpenFileDialog opfMapa;
|
||||||
public Process pythonProcess;
|
public Process pythonProcess;
|
||||||
private string CaminhoSaida = Variaveis.CaminhoSistema + PythonService.CaminhoGeral + PythonService.CaminhoLeitura;
|
private string CaminhoSaida = Variaveis.CaminhoSistema + PythonService.CaminhoGeral + PythonService.CaminhoLeitura;
|
||||||
private string NomeArquivoMapa = "";
|
public string NomeArquivoMapa = "";
|
||||||
public string NomeArquivos = "";
|
public string NomeArquivos = "";
|
||||||
public string CaminhoMapa = "";
|
public string CaminhoMapa = "";
|
||||||
public string ArquivoSaida = "";
|
public string ArquivoSaida = "";
|
||||||
|
|
@ -55,52 +55,22 @@ namespace AgroBase.Services
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void CarregarMapaGPS(string nomeArquivoMapa)
|
||||||
|
{
|
||||||
|
NomeArquivoMapa = nomeArquivoMapa;
|
||||||
|
|
||||||
|
pythonProcess = PythonService.RunScript(PythonService.ScriptMapGPS, new string[] { CaminhoMapa, NomeArquivos, ArquivoSaida, NomeArquivoMapa, APIService.ApiBase() + APIService.GPS_getCoordenadasEndpoint.Replace("<id>", APIService.GPS_IDcoordenadasRobo.ToString()) });
|
||||||
|
|
||||||
|
MapaUrl = new Uri(CaminhoSaida + NomeArquivoMapa).AbsoluteUri;
|
||||||
|
CaminhoDadosMapa = CaminhoSaida + ArquivoSaida;
|
||||||
|
}
|
||||||
|
|
||||||
public void CarregarDadosMapa()
|
public void CarregarDadosMapa()
|
||||||
{
|
{
|
||||||
var dados = File.ReadAllText(CaminhoDadosMapa);
|
var dados = File.ReadAllText(CaminhoDadosMapa);
|
||||||
DadosMapa = JsonConvert.DeserializeObject<MapaFeatureCollectionModel>(dados);
|
DadosMapa = JsonConvert.DeserializeObject<MapaFeatureCollectionModel>(dados);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void CarregarMapaGPS(string nomeArquivoMapa)
|
|
||||||
{
|
|
||||||
NomeArquivoMapa = nomeArquivoMapa;
|
|
||||||
|
|
||||||
pythonProcess = PythonService.RunScript(PythonService.ScriptMapGPS, new string[] { VariaveisPortas.GPS.ToString(), PathUpdateMarker });
|
|
||||||
|
|
||||||
MapaUrl = new Uri("http://localhost:" + VariaveisPortas.GPS + "/").AbsoluteUri;
|
|
||||||
|
|
||||||
//MapaUrl = new Uri(Variaveis.CaminhoSistema + "Utils\\offline_maps\\index.html").AbsoluteUri;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async void AtualizarPosicaoMapaGPS(double lat, double lon)
|
|
||||||
{
|
|
||||||
HttpClient _client = new HttpClient();
|
|
||||||
|
|
||||||
var payload = new
|
|
||||||
{
|
|
||||||
lat = lat,
|
|
||||||
lon = lon
|
|
||||||
};
|
|
||||||
|
|
||||||
var content = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json");
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var response = await _client.PostAsync(MapaUrl + PathUpdateMarker, content);
|
|
||||||
if (response.IsSuccessStatusCode)
|
|
||||||
{
|
|
||||||
Console.WriteLine("Localização atualizada com sucesso!");
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
Console.WriteLine("Erro ao atualizar a localização.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (HttpRequestException ex)
|
|
||||||
{
|
|
||||||
Console.WriteLine($"Erro de requisição: {ex.Message}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Binary file not shown.
|
|
@ -0,0 +1,160 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
|
||||||
|
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
|
||||||
|
|
||||||
|
<script>
|
||||||
|
L_NO_TOUCH = false;
|
||||||
|
L_DISABLE_3D = false;
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style>html, body {width: 100%;height: 100%;margin: 0;padding: 0;}</style>
|
||||||
|
<style>#map {position:absolute;top:0;bottom:0;right:0;left:0;}</style>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/leaflet@1.9.3/dist/leaflet.js"></script>
|
||||||
|
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
|
||||||
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.js"></script>
|
||||||
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet@1.9.3/dist/leaflet.css"/>
|
||||||
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css"/>
|
||||||
|
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"/>
|
||||||
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.2.0/css/all.min.css"/>
|
||||||
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.css"/>
|
||||||
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/python-visualization/folium/folium/templates/leaflet.awesome.rotate.min.css"/>
|
||||||
|
|
||||||
|
<meta name="viewport" content="width=device-width,
|
||||||
|
initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
|
||||||
|
<style>
|
||||||
|
#map_70e636f4a8ced6e9b5e05eeaa5305e16 {
|
||||||
|
position: relative;
|
||||||
|
width: 100.0%;
|
||||||
|
height: 100.0%;
|
||||||
|
left: 0.0%;
|
||||||
|
top: 0.0%;
|
||||||
|
}
|
||||||
|
.leaflet-container { font-size: 1rem; }
|
||||||
|
</style>
|
||||||
|
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
|
||||||
|
<div class="folium-map" id="map_70e636f4a8ced6e9b5e05eeaa5305e16" ></div>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
<script>
|
||||||
|
|
||||||
|
|
||||||
|
var map_70e636f4a8ced6e9b5e05eeaa5305e16 = L.map(
|
||||||
|
"map_70e636f4a8ced6e9b5e05eeaa5305e16",
|
||||||
|
{
|
||||||
|
center: [0.0, 0.0],
|
||||||
|
crs: L.CRS.EPSG3857,
|
||||||
|
zoom: 12,
|
||||||
|
zoomControl: true,
|
||||||
|
preferCanvas: false,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var tile_layer_4bde257ec25fe71bb2cdd06d86be29a2 = L.tileLayer(
|
||||||
|
"https://tile.openstreetmap.org/{z}/{x}/{y}.png",
|
||||||
|
{"attribution": "\u0026copy; \u003ca href=\"https://www.openstreetmap.org/copyright\"\u003eOpenStreetMap\u003c/a\u003e contributors", "detectRetina": false, "maxNativeZoom": 19, "maxZoom": 19, "minZoom": 0, "noWrap": false, "opacity": 1, "subdomains": "abc", "tms": false}
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
tile_layer_4bde257ec25fe71bb2cdd06d86be29a2.addTo(map_70e636f4a8ced6e9b5e05eeaa5305e16);
|
||||||
|
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
function trajeto_json_onEachFeature(feature, layer) {
|
||||||
|
layer.on({
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var trajeto_json = L.geoJson(null, {
|
||||||
|
onEachFeature: trajeto_json_onEachFeature,
|
||||||
|
style: function(feature) {
|
||||||
|
return {color: 'red'};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
function trajeto_json_add (data) {
|
||||||
|
trajeto_json.addData(data);
|
||||||
|
}
|
||||||
|
trajeto_json_add({"features": []});
|
||||||
|
|
||||||
|
trajeto_json.addTo(map_70e636f4a8ced6e9b5e05eeaa5305e16);
|
||||||
|
|
||||||
|
function adicionarGeometria(novaGeometria) {
|
||||||
|
trajeto_json.addData(novaGeometria);
|
||||||
|
}
|
||||||
|
|
||||||
|
function saoCoordenadasIguais(coord1, coord2, tolerancia) {
|
||||||
|
return Math.abs(coord1[0] - coord2[0]) < tolerancia && Math.abs(coord1[1] - coord2[1]) < tolerancia;
|
||||||
|
}
|
||||||
|
|
||||||
|
function adicionarCoordenada(idGeometria, novaCoordenada) {
|
||||||
|
var feature = trajeto_json.toGeoJSON().features.find(f => f.id === idGeometria);
|
||||||
|
if (feature) {
|
||||||
|
var ultima = [0.0,0.0];
|
||||||
|
if (feature.geometry.coordinates.length > 0) {
|
||||||
|
ultima = feature.geometry.coordinates[feature.geometry.coordinates.length - 1];
|
||||||
|
}
|
||||||
|
if (!saoCoordenadasIguais(ultima, novaCoordenada, 0.000001)) {
|
||||||
|
feature.geometry.coordinates.push(novaCoordenada);
|
||||||
|
var ft = feature;
|
||||||
|
trajeto_json.clearLayers();
|
||||||
|
trajeto_json.addData(ft);
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
console.log("Feature com ID " + idGeometria + " não encontrada.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
adicionarGeometria({
|
||||||
|
"type": "Feature",
|
||||||
|
"geometry": {
|
||||||
|
"type": "LineString",
|
||||||
|
"coordinates": []
|
||||||
|
},
|
||||||
|
"properties": {"Dist1": 0.0, "Dist2": 0.0, "Id": 1517, "Length": 21.724783283, "Name": "Projeto"},
|
||||||
|
"id": "Tj"
|
||||||
|
});
|
||||||
|
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
var marcadorDinamico = L.marker([0, 0], {
|
||||||
|
icon: L.AwesomeMarkers.icon({
|
||||||
|
icon: 'info-sign',
|
||||||
|
markerColor: 'red',
|
||||||
|
prefix: 'glyphicon'
|
||||||
|
})
|
||||||
|
}).addTo(map_70e636f4a8ced6e9b5e05eeaa5305e16);
|
||||||
|
|
||||||
|
function atualizarMarcador() {
|
||||||
|
fetch('http://localhost:5001/servir-coordenadas/1')
|
||||||
|
.then(function(response) {
|
||||||
|
return response.json();
|
||||||
|
})
|
||||||
|
.then(function(dados) {
|
||||||
|
var novaLatitude = dados.latitude;
|
||||||
|
var novaLongitude = dados.longitude;
|
||||||
|
var novaPosicao = [novaLatitude, novaLongitude];
|
||||||
|
marcadorDinamico.setLatLng(novaPosicao);
|
||||||
|
adicionarCoordenada("Tj", [novaLongitude, novaLatitude]);
|
||||||
|
})
|
||||||
|
.catch(function(error) {
|
||||||
|
console.error('Erro ao atualizar o marcador:', error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Atualiza o marcador a cada 2 segundos
|
||||||
|
setInterval(atualizarMarcador, 2000);
|
||||||
|
</script>
|
||||||
|
</html>
|
||||||
|
|
@ -1,40 +1,152 @@
|
||||||
from flask import Flask, jsonify, request
|
import geopandas as gpd
|
||||||
import folium
|
import json
|
||||||
import sys
|
import sys
|
||||||
|
import folium
|
||||||
|
import requests
|
||||||
|
import re
|
||||||
|
|
||||||
app = Flask(__name__)
|
def internet_disponivel():
|
||||||
|
"""Verifica se há conexão com a internet."""
|
||||||
|
url = 'http://www.google.com/'
|
||||||
|
timeout = 5
|
||||||
|
try:
|
||||||
|
_ = requests.get(url, timeout=timeout)
|
||||||
|
return True
|
||||||
|
except requests.ConnectionError:
|
||||||
|
return False
|
||||||
|
|
||||||
# Armazena a última localização conhecida
|
# Argumentos e configurações iniciais
|
||||||
last_known_location = (-22.1839247, -47.3824123)
|
pathFiles = sys.argv[1]
|
||||||
|
fileName = sys.argv[2]
|
||||||
|
outputName = sys.argv[3]
|
||||||
|
outputMapName = sys.argv[4]
|
||||||
|
apiEndpoit = sys.argv[5]
|
||||||
|
pastaSaida = 'Python/Output/'
|
||||||
|
|
||||||
# Rota para renderizar o mapa inicial
|
center = [0, 0]
|
||||||
@app.route('/')
|
|
||||||
def index():
|
|
||||||
global last_known_location
|
|
||||||
folium_map = folium.Map(location=last_known_location, zoom_start=20)
|
|
||||||
folium.Marker(last_known_location, tooltip='Ponto GPS').add_to(folium_map)
|
|
||||||
return folium_map._repr_html_()
|
|
||||||
|
|
||||||
# Rota para atualizar as coordenadas do marcador
|
# Verificar se há conexão com a internet
|
||||||
@app.route('/update_marker', methods=['POST'])
|
if internet_disponivel():
|
||||||
def update_marker():
|
m = folium.Map(location=center, zoom_start=12)
|
||||||
global last_known_location
|
else:
|
||||||
data = request.json
|
m = folium.Map(location=center, zoom_start=12, tiles=None)
|
||||||
last_known_location = (data['lat'], data['lon'])
|
|
||||||
return jsonify({'message': 'Coordenadas atualizadas com sucesso!'}), 200
|
|
||||||
|
|
||||||
# Rota para obter as coordenadas do marcador
|
# Salvar o mapa interativo em um arquivo HTML
|
||||||
@app.route('/get_marker')
|
m.save(pastaSaida + outputMapName)
|
||||||
def get_marker():
|
|
||||||
global last_known_location
|
|
||||||
return jsonify(last_known_location)
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
port = 5000 # Porta padrão
|
# Caminho completo para o arquivo HTML gerado
|
||||||
if len(sys.argv) > 1:
|
caminho_completo_html = pastaSaida + outputMapName
|
||||||
try:
|
|
||||||
port = int(sys.argv[1])
|
# Abrir o arquivo HTML para leitura e escrita
|
||||||
except ValueError:
|
with open(caminho_completo_html, 'r+') as arquivo_html:
|
||||||
print("Por favor forneça um número de porta válido.")
|
# Ler o conteúdo do arquivo
|
||||||
sys.exit(1)
|
conteudo_html = arquivo_html.read()
|
||||||
app.run(debug=True, port=port)
|
|
||||||
|
# Usar expressão regular para encontrar o ID do mapa
|
||||||
|
padrao_id_mapa = re.compile(r'id="map_(.*?)"')
|
||||||
|
resultado_busca = padrao_id_mapa.search(conteudo_html)
|
||||||
|
|
||||||
|
# Verificar se encontrou um ID de mapa
|
||||||
|
if resultado_busca:
|
||||||
|
id_mapa = 'map_' + resultado_busca.group(1)
|
||||||
|
else:
|
||||||
|
raise ValueError("Não foi possível encontrar o ID do mapa no arquivo HTML.")
|
||||||
|
|
||||||
|
# Script JavaScript para adicionar ao HTML, com o ID do mapa substituído
|
||||||
|
script_atualizacao_marcador = f"""
|
||||||
|
<script>
|
||||||
|
function trajeto_json_onEachFeature(feature, layer) {{
|
||||||
|
layer.on({{
|
||||||
|
}});
|
||||||
|
}};
|
||||||
|
var trajeto_json = L.geoJson(null, {{
|
||||||
|
onEachFeature: trajeto_json_onEachFeature,
|
||||||
|
style: function(feature) {{
|
||||||
|
return {{color: 'red'}};
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
);
|
||||||
|
function trajeto_json_add (data) {{
|
||||||
|
trajeto_json.addData(data);
|
||||||
|
}}
|
||||||
|
trajeto_json_add({{"features": []}});
|
||||||
|
|
||||||
|
trajeto_json.addTo({id_mapa});
|
||||||
|
|
||||||
|
function adicionarGeometria(novaGeometria) {{
|
||||||
|
trajeto_json.addData(novaGeometria);
|
||||||
|
}}
|
||||||
|
|
||||||
|
function saoCoordenadasIguais(coord1, coord2, tolerancia) {{
|
||||||
|
return Math.abs(coord1[0] - coord2[0]) < tolerancia && Math.abs(coord1[1] - coord2[1]) < tolerancia;
|
||||||
|
}}
|
||||||
|
|
||||||
|
function adicionarCoordenada(idGeometria, novaCoordenada) {{
|
||||||
|
var feature = trajeto_json.toGeoJSON().features.find(f => f.id === idGeometria);
|
||||||
|
if (feature) {{
|
||||||
|
var ultima = [0.0,0.0];
|
||||||
|
if (feature.geometry.coordinates.length > 0) {{
|
||||||
|
ultima = feature.geometry.coordinates[feature.geometry.coordinates.length - 1];
|
||||||
|
}}
|
||||||
|
if (!saoCoordenadasIguais(ultima, novaCoordenada, 0.000001)) {{
|
||||||
|
feature.geometry.coordinates.push(novaCoordenada);
|
||||||
|
var ft = feature;
|
||||||
|
trajeto_json.clearLayers();
|
||||||
|
trajeto_json.addData(ft);
|
||||||
|
}}
|
||||||
|
|
||||||
|
}} else {{
|
||||||
|
console.log("Feature com ID " + idGeometria + " não encontrada.");
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
|
||||||
|
adicionarGeometria({{
|
||||||
|
"type": "Feature",
|
||||||
|
"geometry": {{
|
||||||
|
"type": "LineString",
|
||||||
|
"coordinates": []
|
||||||
|
}},
|
||||||
|
"properties": {{"Dist1": 0.0, "Dist2": 0.0, "Id": 1517, "Length": 21.724783283, "Name": "Projeto"}},
|
||||||
|
"id": "Tj"
|
||||||
|
}});
|
||||||
|
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
var marcadorDinamico = L.marker([0, 0], {{
|
||||||
|
icon: L.AwesomeMarkers.icon({{
|
||||||
|
icon: 'info-sign',
|
||||||
|
markerColor: 'red',
|
||||||
|
prefix: 'glyphicon'
|
||||||
|
}})
|
||||||
|
}}).addTo({id_mapa});
|
||||||
|
|
||||||
|
function atualizarMarcador() {{
|
||||||
|
fetch('{apiEndpoit}')
|
||||||
|
.then(function(response) {{
|
||||||
|
return response.json();
|
||||||
|
}})
|
||||||
|
.then(function(dados) {{
|
||||||
|
var novaLatitude = dados.latitude;
|
||||||
|
var novaLongitude = dados.longitude;
|
||||||
|
var novaPosicao = [novaLatitude, novaLongitude];
|
||||||
|
marcadorDinamico.setLatLng(novaPosicao);
|
||||||
|
adicionarCoordenada("Tj", [novaLongitude, novaLatitude]);
|
||||||
|
}})
|
||||||
|
.catch(function(error) {{
|
||||||
|
console.error('Erro ao atualizar o marcador:', error);
|
||||||
|
}});
|
||||||
|
}}
|
||||||
|
|
||||||
|
// Atualiza o marcador a cada 2 segundos
|
||||||
|
setInterval(atualizarMarcador, 2000);
|
||||||
|
</script>
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Inserir o script no conteúdo HTML
|
||||||
|
conteudo_atualizado = conteudo_html.replace('</html>', script_atualizacao_marcador + '</html>')
|
||||||
|
|
||||||
|
# Agora, reabrir o arquivo para escrita e sobrescrever o conteúdo com a versão atualizada
|
||||||
|
with open(caminho_completo_html, 'w') as arquivo_html:
|
||||||
|
arquivo_html.write(conteudo_atualizado)
|
||||||
Binary file not shown.
Binary file not shown.
Loading…
Reference in New Issue