diff --git a/AgroBase/.vs/AgroBase/FileContentIndex/65d2fec8-5d52-43ed-8bcc-7cc233a305a8.vsidx b/AgroBase/.vs/AgroBase/FileContentIndex/65d2fec8-5d52-43ed-8bcc-7cc233a305a8.vsidx deleted file mode 100644 index b9496c197..000000000 Binary files a/AgroBase/.vs/AgroBase/FileContentIndex/65d2fec8-5d52-43ed-8bcc-7cc233a305a8.vsidx and /dev/null differ diff --git a/AgroBase/.vs/AgroBase/FileContentIndex/faad9eff-0b41-46b2-a28c-f1fdcdd9a315.vsidx b/AgroBase/.vs/AgroBase/FileContentIndex/87e55ef8-b317-418c-bad0-b5de01033ce7.vsidx similarity index 55% rename from AgroBase/.vs/AgroBase/FileContentIndex/faad9eff-0b41-46b2-a28c-f1fdcdd9a315.vsidx rename to AgroBase/.vs/AgroBase/FileContentIndex/87e55ef8-b317-418c-bad0-b5de01033ce7.vsidx index 7e890a6ac..a88d9a389 100644 Binary files a/AgroBase/.vs/AgroBase/FileContentIndex/faad9eff-0b41-46b2-a28c-f1fdcdd9a315.vsidx and b/AgroBase/.vs/AgroBase/FileContentIndex/87e55ef8-b317-418c-bad0-b5de01033ce7.vsidx differ diff --git a/AgroBase/.vs/AgroBase/FileContentIndex/c5c345b0-df0b-4c4a-85f3-5a3a75bbec37.vsidx b/AgroBase/.vs/AgroBase/FileContentIndex/c5c345b0-df0b-4c4a-85f3-5a3a75bbec37.vsidx deleted file mode 100644 index 0b2ace82f..000000000 Binary files a/AgroBase/.vs/AgroBase/FileContentIndex/c5c345b0-df0b-4c4a-85f3-5a3a75bbec37.vsidx and /dev/null differ diff --git a/AgroBase/.vs/AgroBase/FileContentIndex/f2145916-ae0b-4f5f-83ae-a3bd17bfc1a3.vsidx b/AgroBase/.vs/AgroBase/FileContentIndex/f2145916-ae0b-4f5f-83ae-a3bd17bfc1a3.vsidx new file mode 100644 index 000000000..b50e7801a Binary files /dev/null and b/AgroBase/.vs/AgroBase/FileContentIndex/f2145916-ae0b-4f5f-83ae-a3bd17bfc1a3.vsidx differ diff --git a/AgroBase/.vs/AgroBase/FileContentIndex/fb5cbd4d-84a7-46e0-a883-910e20a0a6bc.vsidx b/AgroBase/.vs/AgroBase/FileContentIndex/fb5cbd4d-84a7-46e0-a883-910e20a0a6bc.vsidx new file mode 100644 index 000000000..bcb2df67a Binary files /dev/null and b/AgroBase/.vs/AgroBase/FileContentIndex/fb5cbd4d-84a7-46e0-a883-910e20a0a6bc.vsidx differ diff --git a/AgroBase/.vs/AgroBase/v17/.suo b/AgroBase/.vs/AgroBase/v17/.suo index 0a328545c..d866cb87a 100644 Binary files a/AgroBase/.vs/AgroBase/v17/.suo and b/AgroBase/.vs/AgroBase/v17/.suo differ diff --git a/AgroBase/AgroBase/Forms/frmGPS.cs b/AgroBase/AgroBase/Forms/frmGPS.cs index 77513d308..a5a8abfd2 100644 --- a/AgroBase/AgroBase/Forms/frmGPS.cs +++ b/AgroBase/AgroBase/Forms/frmGPS.cs @@ -1,4 +1,5 @@ -using AgroBase.Services; +using AgroBase.Models; +using AgroBase.Services; using CefSharp; using CefSharp.WinForms; using System; @@ -8,13 +9,16 @@ namespace AgroBase.Forms { public partial class frmGPS : Form { - private ChromiumWebBrowser chromiumWebBrowser; - private MapasService mapaService = new MapasService(); - Timer tmrUpdate = new Timer(); + private MapasModel Mapa; public frmGPS() { InitializeComponent(); + + Mapa = new MapasModel() + { + pnlMapa = pnlMapa, + }; } private void frmGPS_Load(object sender, EventArgs e) @@ -24,58 +28,12 @@ namespace AgroBase.Forms private void frmGPS_FormClosing(object sender, FormClosingEventArgs e) { - try - { - GPSService.PararRecepcaoDados(); - - tmrUpdate.Stop(); - mapaService.pythonProcess.Kill(); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - } + Mapa.PararProcessamento(); } private void IniciarMapa() { - GPSService.IniciarRecepcaoDados(); - - 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; - } + Mapa.CarregarMapaGPS(); } diff --git a/AgroBase/AgroBase/Forms/frmPrincipal.cs b/AgroBase/AgroBase/Forms/frmPrincipal.cs index 19cf9694c..8aa48cd4a 100644 --- a/AgroBase/AgroBase/Forms/frmPrincipal.cs +++ b/AgroBase/AgroBase/Forms/frmPrincipal.cs @@ -251,6 +251,7 @@ namespace AgroBase 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 AtuConectado = Variaveis.DispositivosConectados.Any(x => x.Dispositivo == T_Code.Atu && (x._Porta.IsOpen || DebugMode)); + bool GpsConectado = GPSService.PortaGPS != null; 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 != "") { diff --git a/AgroBase/AgroBase/Models/MapasModel.cs b/AgroBase/AgroBase/Models/MapasModel.cs index ea42aae8c..6e6710d5f 100644 --- a/AgroBase/AgroBase/Models/MapasModel.cs +++ b/AgroBase/AgroBase/Models/MapasModel.cs @@ -35,6 +35,14 @@ namespace AgroBase.Models 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) { if (mapaService.pythonProcess.HasExited) @@ -42,14 +50,31 @@ namespace AgroBase.Models ((Timer)sender).Stop(); picLoading.Visible = false; - mapaService.CarregarDadosMapa(); + if (mapaService.NomeArquivoMapa == MapasVariaveisModel.NomeArquivoMapaInterativo) + { + mapaService.CarregarDadosMapa(); + lblMapa.Text = "Mapa carregado: " + mapaService.NomeArquivos; + } - lblMapa.Text = "Mapa carregado: " + mapaService.NomeArquivos; - chromiumWebBrowser = new ChromiumWebBrowser(mapaService.MapaUrl); - pnlMapa.Controls.Add(chromiumWebBrowser); - chromiumWebBrowser.Dock = DockStyle.Fill; + IniciarProcessamento(); } } + + 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 diff --git a/AgroBase/AgroBase/Python/Scripts/gps-viewer.py b/AgroBase/AgroBase/Python/Scripts/gps-viewer.py index 287f4a5ec..79a5a1432 100644 --- a/AgroBase/AgroBase/Python/Scripts/gps-viewer.py +++ b/AgroBase/AgroBase/Python/Scripts/gps-viewer.py @@ -1,40 +1,152 @@ -from flask import Flask, jsonify, request -import folium +import geopandas as gpd +import json 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 -last_known_location = (-22.1839247, -47.3824123) +# Argumentos e configurações iniciais +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 -@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_() +center = [0, 0] -# Rota para atualizar as coordenadas do marcador -@app.route('/update_marker', methods=['POST']) -def update_marker(): - global last_known_location - data = request.json - last_known_location = (data['lat'], data['lon']) - return jsonify({'message': 'Coordenadas atualizadas com sucesso!'}), 200 +# Verificar se há conexão com a internet +if internet_disponivel(): + m = folium.Map(location=center, zoom_start=12) +else: + m = folium.Map(location=center, zoom_start=12, tiles=None) -# Rota para obter as coordenadas do marcador -@app.route('/get_marker') -def get_marker(): - global last_known_location - return jsonify(last_known_location) +# Salvar o mapa interativo em um arquivo HTML +m.save(pastaSaida + outputMapName) -if __name__ == '__main__': - port = 5000 # Porta padrão - if len(sys.argv) > 1: - try: - port = int(sys.argv[1]) - except ValueError: - print("Por favor forneça um número de porta válido.") - sys.exit(1) - app.run(debug=True, port=port) \ No newline at end of file + +# Caminho completo para o arquivo HTML gerado +caminho_completo_html = pastaSaida + outputMapName + +# Abrir o arquivo HTML para leitura e escrita +with open(caminho_completo_html, 'r+') as arquivo_html: + # Ler o conteúdo do arquivo + conteudo_html = arquivo_html.read() + + # 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""" + + + + """ + +# Inserir o script no conteúdo HTML +conteudo_atualizado = conteudo_html.replace('', script_atualizacao_marcador + '') + +# 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) \ No newline at end of file diff --git a/AgroBase/AgroBase/Services/MapasService.cs b/AgroBase/AgroBase/Services/MapasService.cs index cd4a097f5..a7fac3c6d 100644 --- a/AgroBase/AgroBase/Services/MapasService.cs +++ b/AgroBase/AgroBase/Services/MapasService.cs @@ -21,7 +21,7 @@ namespace AgroBase.Services OpenFileDialog opfMapa; public Process pythonProcess; private string CaminhoSaida = Variaveis.CaminhoSistema + PythonService.CaminhoGeral + PythonService.CaminhoLeitura; - private string NomeArquivoMapa = ""; + public string NomeArquivoMapa = ""; public string NomeArquivos = ""; public string CaminhoMapa = ""; 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("", APIService.GPS_IDcoordenadasRobo.ToString()) }); + + MapaUrl = new Uri(CaminhoSaida + NomeArquivoMapa).AbsoluteUri; + CaminhoDadosMapa = CaminhoSaida + ArquivoSaida; + } + public void CarregarDadosMapa() { var dados = File.ReadAllText(CaminhoDadosMapa); DadosMapa = JsonConvert.DeserializeObject(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}"); - } - } } } diff --git a/AgroBase/AgroBase/bin/Debug/AgroBase.pdb b/AgroBase/AgroBase/bin/Debug/AgroBase.pdb index e6748bd7a..5b3d55add 100644 Binary files a/AgroBase/AgroBase/bin/Debug/AgroBase.pdb and b/AgroBase/AgroBase/bin/Debug/AgroBase.pdb differ diff --git a/AgroBase/AgroBase/bin/Debug/Python/Output/mapa_gps.html b/AgroBase/AgroBase/bin/Debug/Python/Output/mapa_gps.html new file mode 100644 index 000000000..7d85cfbd4 --- /dev/null +++ b/AgroBase/AgroBase/bin/Debug/Python/Output/mapa_gps.html @@ -0,0 +1,160 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + \ No newline at end of file diff --git a/AgroBase/AgroBase/bin/Debug/Python/Scripts/gps-viewer.py b/AgroBase/AgroBase/bin/Debug/Python/Scripts/gps-viewer.py index 287f4a5ec..79a5a1432 100644 --- a/AgroBase/AgroBase/bin/Debug/Python/Scripts/gps-viewer.py +++ b/AgroBase/AgroBase/bin/Debug/Python/Scripts/gps-viewer.py @@ -1,40 +1,152 @@ -from flask import Flask, jsonify, request -import folium +import geopandas as gpd +import json 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 -last_known_location = (-22.1839247, -47.3824123) +# Argumentos e configurações iniciais +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 -@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_() +center = [0, 0] -# Rota para atualizar as coordenadas do marcador -@app.route('/update_marker', methods=['POST']) -def update_marker(): - global last_known_location - data = request.json - last_known_location = (data['lat'], data['lon']) - return jsonify({'message': 'Coordenadas atualizadas com sucesso!'}), 200 +# Verificar se há conexão com a internet +if internet_disponivel(): + m = folium.Map(location=center, zoom_start=12) +else: + m = folium.Map(location=center, zoom_start=12, tiles=None) -# Rota para obter as coordenadas do marcador -@app.route('/get_marker') -def get_marker(): - global last_known_location - return jsonify(last_known_location) +# Salvar o mapa interativo em um arquivo HTML +m.save(pastaSaida + outputMapName) -if __name__ == '__main__': - port = 5000 # Porta padrão - if len(sys.argv) > 1: - try: - port = int(sys.argv[1]) - except ValueError: - print("Por favor forneça um número de porta válido.") - sys.exit(1) - app.run(debug=True, port=port) \ No newline at end of file + +# Caminho completo para o arquivo HTML gerado +caminho_completo_html = pastaSaida + outputMapName + +# Abrir o arquivo HTML para leitura e escrita +with open(caminho_completo_html, 'r+') as arquivo_html: + # Ler o conteúdo do arquivo + conteudo_html = arquivo_html.read() + + # 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""" + + + + """ + +# Inserir o script no conteúdo HTML +conteudo_atualizado = conteudo_html.replace('', script_atualizacao_marcador + '') + +# 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) \ No newline at end of file diff --git a/AgroBase/AgroBase/obj/Debug/AgroBase.pdb b/AgroBase/AgroBase/obj/Debug/AgroBase.pdb index e6748bd7a..5b3d55add 100644 Binary files a/AgroBase/AgroBase/obj/Debug/AgroBase.pdb and b/AgroBase/AgroBase/obj/Debug/AgroBase.pdb differ diff --git a/AgroBase/AgroBase/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache b/AgroBase/AgroBase/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache index e245c02dd..d6bb52dcf 100644 Binary files a/AgroBase/AgroBase/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache and b/AgroBase/AgroBase/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache differ