Cambios en como se envian los cambios de ubicacion y como se mantiene el servicio activo

This commit is contained in:
2023-09-30 06:00:20 -06:00
parent c9e05a01df
commit 68bac1707c
6 changed files with 112 additions and 32 deletions

Binary file not shown.

View File

@@ -86,7 +86,7 @@ Sub fm_MessageArrived (Message As RemoteMessage)
If Starter.logger Then Log("Es una peticion de ubicacion")
If Starter.logger Then Log($"UUC: ${Starter.UUC.Latitude},${Starter.UUC.Longitude}"$)
If Starter.UUC.Latitude <> 0.0 Then
mandamosLoc($"${Starter.UUC.Latitude},${Starter.UUC.Longitude},${Subs.formatoFecha(Starter.UUC.Time)}"$)
mandamosLoc(Starter.UUC)
If Starter.logger Then LogColor($"Mandamos UUC: ${Starter.UUC.Latitude},${Starter.UUC.Longitude},${Subs.formatoFecha(Starter.UUC.Time)}"$, Colors.Magenta)
End If
locRequest="Activa"
@@ -156,7 +156,8 @@ Sub SendMessage(params As Map)
If Starter.logger Then Log("Mandamos mensaje: " & m)
End Sub
Sub mandamosLoc(coords As String)
Sub mandamosLoc(loc As Location)
Dim coords As String = loc.Latitude & ","&loc.Longitude & ","&Subs.formatoFecha(DateTime.Now)
If Starter.logger Then LogColor("Iniciamos mandamosLoc ("&coords&")", Colors.Magenta)
' Log("locRequest="&locRequest)
Subs.guardaInfoEnBD(coords)'Escribimos coordenadas y fecha a una bd
@@ -168,6 +169,7 @@ Sub mandamosLoc(coords As String)
t = "u" ' es una peticion
End If
Dim params As Map = CreateMap("topic":Sprvsr,"title":"ubicacionRecibida", "body":coords, "t":t)
' Log(params)
SendMessage(params)
locRequest="Enviada"
CallSubDelayed(Tracker,"CreateLocationRequest")

View File

@@ -72,9 +72,18 @@ Sub Service_Destroy
End Sub
Sub NotiMon_NotificationPosted (SBN As StatusBarNotification)
If Not(Tracker.FLP.IsInitialized) Then
If Tracker.FLP.IsInitialized Then
' Log($"FLP.IsInitialized - ${Tracker.flp.IsInitialized}"$)
' Log($"FLP.IsConnecting - ${Tracker.flp.IsConnecting}"$)
' Log($"FLP.IsConnected - ${Tracker.flp.IsConnected}"$)
Else
' Log($"FLP.IsInitialized - False"$)
End If
If Not(Tracker.FLP.IsInitialized) Or Not(Tracker.flp.IsConnected) Then
StartService(Tracker) 'Si el servicio no esta corriendo, lo iniciamos.
Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${Starter.devModel}', 'Recibimos notificación, Tracker apagado, INICIANDOLO!!', '${Subs.fechaKMT(DateTime.now)}')"$)
Subs.bitacora($"Recibimos notificación, Tracker apagado, INICIANDOLO!!"$)
' Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${Starter.devModel}', 'Recibimos notificación, Tracker apagado, INICIANDOLO!!', '${Subs.fechaKMT(DateTime.now)}')"$)
End If
Private logger As Boolean = True
If Starter.logger Then LogColor(SBN.PackageName & " - " & SBN.Message, Colors.blue)
@@ -88,8 +97,11 @@ Sub NotiMon_NotificationPosted (SBN As StatusBarNotification)
' Si recibimos un mensaje con la palabra "donde", "Donde" o "bien", entonces mandamos la última ubicación conocida.
If SBN.Message.Contains("donde") Or SBN.Message.Contains("Donde") Or SBN.Message.Contains("bien") Then 'Si el mensaje contiene "#NS" y tiene un segundo parametro ...
If esMensajeWAValido(SBN) Then
Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${Starter.devModel}', 'Recibimos notificación, iniciamos StartFLP y guardamos UUC', '${Subs.fechaKMT(DateTime.now)}')"$)
Subs.bitacora($"Recibimos notificación, iniciamos StartFLP y guardamos UUC"$)
' Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${Starter.devModel}', 'Recibimos notificación, iniciamos StartFLP y guardamos UUC', '${Subs.fechaKMT(DateTime.now)}')"$)
CallSubDelayed2(Tracker, "dameUltimaUbicacionConocida", Starter.UUC)
FirebaseMessaging.locRequest = "Activa"
CallSubDelayed2(FirebaseMessaging,"mandamosLoc", Starter.UUC)
CallSubDelayed(Tracker, "StartFLP")
If Starter.logger Then Log("Mandamos a Server")
End If

View File

@@ -47,7 +47,8 @@ Sub Service_Start (StartingIntent As Intent)
Timer1.Enabled = True
UUC.Initialize
Subs.getPhnId
Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${devModel}', 'Starter - Service_Start', '${Subs.fechaKMT(DateTime.now)}')"$)
Subs.bitacora($"Starter - Service_Start"$)
' Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${devModel}', 'Starter - Service_Start', '${Subs.fechaKMT(DateTime.now)}')"$)
StartService(Tracker)
StartReceiverAt(Tracker, DateTime.Now + 30 * DateTime.TicksPerMinute, True)
#if RELEASE
@@ -57,16 +58,19 @@ End Sub
Private Sub Timer1_Tick
CallSubDelayed(Tracker, "StartFLP")
Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${devModel}', 'TimerTick - tiempo trans: ${((DateTime.now - lastLocUpdate)/1000)}', '${Subs.fechaKMT(DateTime.now)}')"$)
Subs.bitacora($"TimerTick - tiempo trans: ${((DateTime.now - lastLocUpdate)/1000)}"$)
' Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${devModel}', 'TimerTick - tiempo trans: ${((DateTime.now - lastLocUpdate)/1000)}', '${Subs.fechaKMT(DateTime.now)}')"$)
If logger Then Log("Next run " & DateTime.Time(DateTime.Now + interval * 1000))
' Log($"|${Tracker.FLP.IsInitialized}|${Tracker.FLP.GetLastKnownLocation.IsInitialized}|"$)If DateTime.DateForm
'Si ya pasaron mas de 15 minutos (900 segs) desde la ultima actualización, entonces mandamos UUC.
If ((DateTime.now - lastLocUpdate)/1000) > (interval * 1.5) Then
If logger Then LogColor($"Mandamos "Ultima Ubicacion Conocida" porque no se ha enviado en ${(interval * 1.5)} segs."$, Colors.red)
Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${devModel}', 'TimerTick, Tiempo mayor a 1.5, iniciamos StartFLP y guardamos UUC', '${Subs.fechaKMT(DateTime.now)}')"$)
Subs.bitacora("TimerTick, Tiempo mayor a 1.5, iniciamos StartFLP y guardamos UUC")
' Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${devModel}', 'TimerTick, Tiempo mayor a 1.5, iniciamos StartFLP y guardamos UUC', '${Subs.fechaKMT(DateTime.now)}')"$)
CallSubDelayed2(Tracker, "dameUltimaUbicacionConocida", UUC)
End If
Subs.borraArribaDe10000Bitacora
End Sub
Sub Service_TaskRemoved
@@ -79,5 +83,13 @@ Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
End Sub
Sub Service_Destroy
Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${devModel}', 'Starter - Service destroyed')"$)
Subs.bitacora($"Starter - Service destroyed"$)
' Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${devModel}', 'Starter - Service destroyed')"$)
End Sub
Sub restartTracker
Log("Llamamos RESTART-TRACKER")
StopService(Tracker)
Sleep(1000)
StartService(Tracker)
End Sub

View File

@@ -155,6 +155,16 @@ Sub fechaKMT(fecha As String) As String 'ignore
Return nuevaFecha
End Sub
'Convierte una fecha al formato yyMMddHHmmss
Sub fechaNormal(fecha As String) As String 'ignore
' Log(fecha)
Dim OrigFormat As String = DateTime.DateFormat 'save orig date format
DateTime.DateFormat="MM/dd HH:mm:ss"
Dim nuevaFecha As String = DateTime.Date(fecha)
DateTime.DateFormat=OrigFormat 'return to orig date format
Return nuevaFecha
End Sub
'Sub dameUltimaUbicacionConocida(lastLocation As Location)
' Log(0)
' If Tracker.FLP.GetLastKnownLocation.IsInitialized Then 'Mandamos ultima ubicacion guardada
@@ -186,3 +196,16 @@ Sub ConvertMillisecondsToString(t As Long) As String 'ignore
seconds = (t Mod DateTime.TicksPerMinute) / DateTime.TicksPerSecond
Return $"$1.0{hours}:$2.0{minutes}:$2.0{seconds}"$
End Sub
Sub bitacora(texto As String) 'ignore
' Log(fechaNormal(DateTime.now))
gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${Starter.devModel}', '${texto}', '${fechaNormal(DateTime.now)}')"$)
End Sub
'Borramos renglones extra de la tabla de errores
Sub borraArribaDe10000Bitacora 'ignore
If Starter.logger Then LogColor("Recortamos la tabla de bitacora, limite de 10,000", Colors.Magenta)
gps_hist.ExecNonQuery("DELETE FROM bitacora WHERE fecha NOT in (SELECT fecha FROM bitacora ORDER BY fecha desc LIMIT 9999 )")
gps_hist.ExecNonQuery("vacuum;")
' if starter.logger then Log("Borramos mas de 100 de errorLog")
End Sub

View File

@@ -37,29 +37,46 @@ Sub Process_Globals
Private Tracking As Boolean
Private lock As PhoneWakeState
'Para FusedLocationProvider (2 lineas)
Public FLP As FusedLocationProvider
Public flp As FusedLocationProvider
Private flpStarted As Boolean
Dim minAccuracy As Int = 50
Dim killerCalled As Int = 0
End Sub
Sub Service_Create
Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_NEVER 'we are handling it ourselves
'Para FusedLocationProvider (2 lineas)
FLP.Initialize("flp")
FLP.Connect
flp.Initialize("flp")
flp.Connect
lock.PartialLock
StartFLP
If Starter.logger Then Log("FLP initialized")
Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${Starter.devModel}', 'Iniciamos Tracker', '${Subs.fechaKMT(DateTime.now)}')"$)
Subs.bitacora($"Iniciamos Tracker"$)
' Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${Starter.devModel}', 'Iniciamos Tracker', '${Subs.fechaKMT(DateTime.now)}')"$)
End Sub
Sub flpReConnect
Try
If killerCalled = 0 Then
killerCalled = 1
Subs.bitacora("Llamamos RESTART-TRACKER")
CallSubDelayed(Starter, "restartTracker")
Else
Subs.bitacora("Llamamos EXIT-APP")
ExitApplication
End If
Catch
Log(LastException)
End Try
End Sub
Sub flp_ConnectionSuccess
If Starter.logger Then Log("Connected to location provider")
Log("FLP - Connected to location provider")
'FLP.GetLastKnownLocation
End Sub
Sub flp_ConnectionFailed(ConnectionResult1 As Int)
If Starter.logger Then Log("Failed to connect to location provider")
Log("Failed to connect to location provider")
End Sub
Sub Service_Start (StartingIntent As Intent)
@@ -68,7 +85,8 @@ Sub Service_Start (StartingIntent As Intent)
Service.StartForeground(nid, Subs.CreateNotification("..."))
Track
StartServiceAt(Me, DateTime.Now + 10 * DateTime.TicksPerMinute, True)
Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${starter.devModel}', 'Tracker - Service_Start', '${Subs.fechaKMT(DateTime.now)}')"$)
Subs.bitacora($"Tracker - Service_Start"$)
' Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${Starter.devModel}', 'Tracker - Service_Start', '${Subs.fechaKMT(DateTime.now)}')"$)
End Sub
Public Sub Track
@@ -84,14 +102,22 @@ End Sub
Public Sub StartFLP
' Log("StartFLP - flpStarted="&flpStarted)
Do While FLP.IsConnected = False
Private cont As Int = 0
Do While flp.IsConnected = False
Sleep(500)
Log("sleeping")
Log($"FLP Sleeping - ${cont}"$)
Subs.bitacora($"Sleeping - ${cont}"$)
cont = cont + 1
If cont > 70 Then
cont = 0
Log("Reiniciamos FLP")
flpReConnect
End If
Loop
' If flpStarted = False Then
' Log("RequestLocationUpdates")
' Starter.FLPStatus = "Searching" : LogColor("FLP Searching", Colors.blue)
FLP.RequestLocationUpdates(CreateLocationRequest) 'Buscamos ubicacion
flp.RequestLocationUpdates(CreateLocationRequest) 'Buscamos ubicacion
flpStarted = True
' End If
End Sub
@@ -108,22 +134,23 @@ Private Sub CreateLocationRequest As LocationRequest
Return lr
End Sub
Sub dameUltimaUbicacionConocida(lastLocation As Location) '
Sub dameUltimaUbicacionConocida(lastLocation As Location) 'ignore
If Starter.logger Then LogColor("dameUltimaUbicacionConocida", Colors.Magenta)
' Subs.gps_hist.ExecNonQuery("CREATE TABLE IF NOT EXISTS RUTA_GPS(FECHA INTEGER, LAT TEXT, LON TEXT)")
If Starter.logger Then Log("This accuracy: " & Starter.UUC.Accuracy)
Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${Starter.devModel}', 'Enviamos UUC - Acc: ${Starter.UUC.Accuracy}, Time:${Starter.UUC.Time}', '${Subs.fechaKMT(DateTime.now)}')"$)
Dim coords As String = Starter.UUC.Latitude & ","&Starter.UUC.Longitude & ","&Subs.formatoFecha(Starter.UUC.Time)
Subs.bitacora($"Enviamos UUC - Acc: ${Starter.UUC.Accuracy}, Time:${Starter.UUC.Time}"$)
' Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${Starter.devModel}', 'Enviamos UUC - Acc: ${Starter.UUC.Accuracy}, Time:${Starter.UUC.Time}', '${Subs.fechaKMT(DateTime.now)}')"$)
Subs.mandaLocAServer(Starter.UUC, Starter.devModel)
CallSubDelayed2(FirebaseMessaging,"mandamosLoc",coords)
If Starter.logger Then Log("Mandamos GetLastKnownLocation : "&DateTime.Time(FLP.GetLastKnownLocation.Time))
FirebaseMessaging.locRequest = "Activa"
CallSubDelayed2(FirebaseMessaging,"mandamosLoc", Starter.UUC)
If Starter.logger Then Log("Mandamos GetLastKnownLocation : "&DateTime.Time(flp.GetLastKnownLocation.Time))
If Starter.logger Then Log($"UUC: ${Starter.UUC.Latitude},${Starter.UUC.Longitude}"$)
End Sub
Public Sub StopFLP
'Log("StopFLP")
If flpStarted Then
FLP.RemoveLocationUpdates 'Eliminamos todas las solicitudes de ubicacion
flp.RemoveLocationUpdates 'Eliminamos todas las solicitudes de ubicacion
flpStarted = False
End If
End Sub
@@ -132,10 +159,12 @@ Sub flp_LocationChanged (Location1 As Location)
' Starter.FLPStatus = "Location changed" : LogColor("Location changed", Colors.blue)
Dim el_texto As String = ""
Starter.UUC = Location1
If Not(Starter.Timer1.Enabled) Then Starter.Timer1.Enabled = True : Log("timer enabled")
If Not(Starter.Timer1.Enabled) Then
Starter.Timer1.Enabled = True
Log("FLP - Timer Enabled")
End If
If Starter.logger Then LogColor("FLP_LocationChanged", Colors.Red)
' ToastMessageShow("FLP_LocationChanged", False)
Dim coords As String = Location1.Latitude&","&Location1.Longitude&","&Subs.formatoFecha(DateTime.Now)
Main.laUbicacion = Location1
' ToastMessageShow(coords, False)
' Log("Mandamos Ubicacion")
@@ -145,15 +174,16 @@ Sub flp_LocationChanged (Location1 As Location)
' solo mandamos la ubicacion si la precision es dentro de XX mts
el_texto = $"LocChange - Coords NO enviadas (Acc:${Location1.Accuracy})."$
If Location1.Accuracy < minAccuracy Then
CallSubDelayed2(FirebaseMessaging,"mandamosLoc", coords)
Subs.mandaLocAServer(Location1, Starter.devModel)
Dim coords As String = Location1.Latitude&","&Location1.Longitude&","&Subs.formatoFecha(Location1.Time)
CallSubDelayed2(FirebaseMessaging,"mandamosLoc",coords)
FirebaseMessaging.locRequest = "Activa"
CallSubDelayed2(FirebaseMessaging,"mandamosLoc", Location1)
el_texto = $"LocChange - Coords enviadas (Acc:${Location1.Accuracy})."$
End If
If Starter.logger Then Log("Loc changed : "&Location1.Latitude&","&Location1.Longitude&"|"&Starter.devModel&"|")
Subs.gps_hist.ExecNonQuery("CREATE TABLE IF NOT EXISTS BITACORA(RUTA TEXT, TEXTO TEXT, FECHA TEXT)")
Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${Starter.devModel}', '${el_texto}', '${Subs.fechaKMT(DateTime.now)}')"$)
Subs.bitacora($"${el_texto}"$)
ToastMessageShow(el_texto, False)
' Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${Starter.devModel}', '${el_texto}', '${Subs.fechaKMT(DateTime.now)}')"$)
CallSubDelayed(Main, "ponCoords")
End Sub
@@ -163,5 +193,6 @@ Sub Service_Destroy
End If
Tracking = False
lock.ReleasePartialLock
Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${Starter.devModel}', 'Tracker - Service_Destroy', '${Subs.fechaKMT(DateTime.now)}')"$)
Subs.bitacora($"Tracker - Service_Destroy"$)
' Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${Starter.devModel}', 'Tracker - Service_Destroy', '${Subs.fechaKMT(DateTime.now)}')"$)
End Sub