mirror of
https://github.com/cheveguerra/FLP_3.0.git
synced 2026-04-17 19:36:19 +00:00
454 lines
19 KiB
QBasic
454 lines
19 KiB
QBasic
B4A=true
|
|
Group=Default Group
|
|
ModulesStructureVersion=1
|
|
Type=StaticCode
|
|
Version=11
|
|
@EndOfDesignText@
|
|
'Code module
|
|
'Subs in this code module will be accessible from all modules.
|
|
Sub Process_Globals
|
|
'These global variables will be declared once when the application starts.
|
|
'These variables can be accessed from all modules.
|
|
Public GZip As GZipStrings
|
|
Private su As StringUtils
|
|
Dim phn As Phone
|
|
Dim devModel As String
|
|
Dim gps_hist As SQL
|
|
Dim wifi As MLwifi
|
|
Dim ssid As String
|
|
Dim locAntTime As String = "0"
|
|
Dim solicitudFM As Int = 0
|
|
End Sub
|
|
|
|
Sub getPhnId 'Pone el valor de phn.Model en la variable global "devModel"
|
|
Private elId As String
|
|
If File.Exists(File.DirInternal, "phnId.txt") Then
|
|
elId = File.ReadString(File.DirInternal, "phnId.txt")
|
|
Else
|
|
File.WriteString(File.DirInternal, "phnId.txt", "") 'Creamos el archivo
|
|
End If
|
|
If elId.Length < 3 Then 'Si el modelo del archivo es menos de 2, lo sustituimos con devmodel
|
|
devModel = phn.Model
|
|
If devModel.Length > 1 Then elId = devModel
|
|
End If
|
|
If elId.Length < 3 Then 'Si el modelo del archivo es menos de 2, lo sustituimos con android_id
|
|
elId = phn.GetSettings("android_id") 'Intentamos con "android_id"
|
|
End If
|
|
If elId.Length < 3 Then elId = $"dev${DateTime.GetHour(DateTime.Now)}"$
|
|
File.WriteString(File.DirInternal, "phnId.txt", elId) 'Sobreescribimos archivo phnId.txt with elId
|
|
' If Starter.logger Then Log("Escribimos phnId: "&elId&" a "&File.DirInternal&"/phnId.txt")
|
|
Starter.devModel = elId
|
|
' If Starter.logger Then Log(Starter.devModel)
|
|
End Sub
|
|
|
|
Sub compress(str As String) As String ' Compresion
|
|
Dim compressed() As Byte = GZip.compress(str)
|
|
If Starter.logger Then Log($"CompressedBytesLength: ${compressed.Length}"$)
|
|
Dim base64 As String = su.EncodeBase64(compressed)
|
|
If Starter.logger Then Log($"CompressedBytes converted to base64 Length: ${base64.Length}"$)
|
|
If Starter.logger Then Log($"CompressedBytes converted to base64: ${base64}"$)
|
|
Return base64
|
|
End Sub
|
|
|
|
Sub decompress(base64 As String) As String ' Descompresion 'ignore
|
|
Dim decompressedbytes() As Byte = su.DecodeBase64(base64)
|
|
If Starter.logger Then Log($"decompressedbytesLength: ${decompressedbytes.Length}"$)
|
|
Dim bc As ByteConverter
|
|
Dim uncompressed As String = bc.StringFromBytes(decompressedbytes,"UTF8")
|
|
If Starter.logger Then Log($"uncompressedLength: ${uncompressed.Length}"$)
|
|
If Starter.logger Then Log($"Decompressed String = ${uncompressed}"$)
|
|
Return uncompressed
|
|
End Sub
|
|
|
|
Sub formatoFecha(fecha As String) As String 'Convierte una fecha al formato yyMMddHHmmss
|
|
' Log(fecha)
|
|
Dim OrigFormat As String = DateTime.DateFormat 'save orig date format
|
|
DateTime.DateFormat="yyMMddHHmmss"
|
|
Dim lastUpdate As String=DateTime.Date(fecha)
|
|
DateTime.DateFormat=OrigFormat 'return to orig date format
|
|
' Log(lastUpdate)
|
|
Return lastUpdate
|
|
End Sub
|
|
|
|
Sub CreateNotification (Body As String) As Notification
|
|
Dim notification As Notification
|
|
notification.Initialize2(notification.IMPORTANCE_LOW)
|
|
notification.Icon = "icon"
|
|
notification.SetInfo("FLP", Body, Main)
|
|
Return notification
|
|
End Sub
|
|
|
|
Sub guardaInfoEnArchivo(coords As String) 'Escribimos coordenadas y fecha a un archivo de texto 'ignore
|
|
' Cambiamos el formato de la hora
|
|
Dim OrigFormat As String=DateTime.DateFormat 'save orig date format
|
|
DateTime.DateFormat="MMM-dd HH:mm:ss"
|
|
Dim lastUpdate As String=DateTime.Date(DateTime.Now)
|
|
DateTime.DateFormat=OrigFormat 'return to orig date format
|
|
|
|
Dim ubic As String = coords&","&lastUpdate
|
|
Dim out As OutputStream = File.OpenOutput(File.DirRootExternal, "gps.txt", True)
|
|
Dim s As String = ubic & CRLF
|
|
Dim t() As Byte = s.GetBytes("UTF-8")
|
|
out.WriteBytes(t, 0, t.Length)
|
|
out.Close
|
|
End Sub
|
|
|
|
'Guarda la ubicacion dada en la tabla "RUTA_GPS".
|
|
Sub guardaInfoEnBD(loc As Location) 'Escribimos coordenadas y fecha a una BD
|
|
If loc.Latitude <> "0.0" Then
|
|
revisaBD
|
|
Private bearingDiff As String = "31"
|
|
Private distanceDiff As String = "21"
|
|
Private tmpLoc As Location
|
|
If Starter.logger Then Log($"Guardamos ubicacion en db (${loc.Latitude},${loc.Longitude})"$)
|
|
'Traemos la ultima ubicacion guardada.
|
|
Private locAnt As ResultSet = gps_hist.ExecQuery($"select FECHA, LAT, LON, ACC, TIME, ifnull(BEARING, 0) as BEARING, ifnull(BEARING_DIFF, 0) as BEARING_DIFF, ifnull(DISTANCE_DIFF, 0) as DISTANCE_DIFF, ifnull(SPEED, 0) as SPEED, ifnull(ENVIADO, 0) as ENVIADO from RUTA_GPS order by time desc limit 1"$)
|
|
Do While locAnt.NextRow
|
|
'Calculamos el cambio de direccion.
|
|
bearingDiff = loc.Bearing - locAnt.GetString("BEARING")
|
|
If locAnt.GetString("BEARING") > loc.Bearing Then bearingDiff = locAnt.GetString("BEARING") - loc.Bearing
|
|
'Calculamos la distancia recorrida.
|
|
tmpLoc.Initialize2(locAnt.GetString("LAT"), locAnt.GetString("LON"))
|
|
distanceDiff = loc.DistanceTo(tmpLoc)
|
|
' Log($"${loc.Accuracy}, ${distanceDiff}, ${bearingDiff}"$)
|
|
Loop
|
|
' Si la precision es menor a 50 y la dirección cambió o la distancia es mayor a 20 mts, la guardamos.
|
|
If loc.Accuracy < 50 And (bearingDiff > 30 Or distanceDiff > 20) Then
|
|
gps_hist.ExecNonQuery2("INSERT INTO RUTA_GPS(fecha, lat, lon, acc, time, bearing, bearing_diff, distance_diff, speed) VALUES (?,?,?,?,?,?,?,?,?)", Array As Object (fechaKMTms(loc.time),loc.Latitude,loc.Longitude, loc.Accuracy, loc.time, loc.Bearing, bearingDiff, distanceDiff, loc.Speed))
|
|
End If
|
|
End If
|
|
End Sub
|
|
|
|
Sub dameRuta As String
|
|
Dim c As Cursor
|
|
If gps_hist.IsInitialized = False Then gps_hist.Initialize(File.DirInternal, "gps_hist.db", True)
|
|
c = gps_hist.ExecQuery("select FECHA, LAT, LON from RUTA_GPS order by FECHA desc limit 380")
|
|
c.Position = 0
|
|
Dim ruta2 As String = ""
|
|
If c.RowCount>0 Then
|
|
For i=0 To c.RowCount -1
|
|
c.Position=i
|
|
ruta2=ruta2&CRLF&c.GetString("LAT")&","&c.GetString("LON")
|
|
B4XPages.MainPage.fechaRuta = c.GetString("FECHA")
|
|
Next
|
|
End If
|
|
c.Close
|
|
Return compress(ruta2)
|
|
End Sub
|
|
|
|
Sub deleteGPS_DB
|
|
' gps_hist.ExecQuery
|
|
gps_hist.ExecNonQuery("delete from RUTA_GPS")
|
|
gps_hist.ExecNonQuery("vacuum;")
|
|
If Starter.logger Then Log("RUTA_GPS borrada")
|
|
End Sub
|
|
|
|
Sub borramosArchivoGPS
|
|
Dim out As OutputStream = File.OpenOutput(File.DirRootExternal, "gps.txt", False)
|
|
Dim s As String = ""
|
|
Dim t() As Byte = s.GetBytes("UTF-8")
|
|
out.WriteBytes(t, 0, t.Length)
|
|
out.Close
|
|
End Sub
|
|
|
|
Sub revisaBD
|
|
If Not(File.Exists(File.DirInternal, "gps_hist.db")) Then File.Copy(File.DirAssets, "gps_hist.db", File.DirInternal, "gps_hist.db")
|
|
If Not(gps_hist.IsInitialized) Then gps_hist.Initialize(File.DirInternal, "gps_hist.db", True)
|
|
If Not(Starter.errorLog.IsInitialized) Then Starter.errorLog.Initialize(File.DirInternal, "errorLog.db", True)
|
|
gps_hist.ExecNonQuery("CREATE TABLE IF NOT EXISTS BITACORA(RUTA TEXT, TEXTO TEXT, FECHA TEXT)")
|
|
gps_hist.ExecNonQuery("CREATE TABLE IF NOT EXISTS RUTA_GPS(FECHA INTEGER, LAT TEXT, LON TEXT, ACC INT, TIME INT)")
|
|
gps_hist.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_VARIABLES(NOMBRE TEXT, VALOR TEXT)")
|
|
agregaColumna("RUTA_GPS", "BEARING", "TEXT")
|
|
agregaColumna("RUTA_GPS", "BEARING_DIFF", "TEXT")
|
|
agregaColumna("RUTA_GPS", "DISTANCE_DIFF", "TEXT")
|
|
agregaColumna("RUTA_GPS", "SPEED", "TEXT")
|
|
agregaColumna("RUTA_GPS", "ENVIADO", "TEXT")
|
|
End Sub
|
|
|
|
Sub getSSID
|
|
If wifi.isWifiConnected Then
|
|
ssid = wifi.WifiSSID
|
|
End If
|
|
End Sub
|
|
|
|
'Convierte una fecha al formato yyMMddHHmmss
|
|
Sub fechaKMT(fecha As String) As String 'ignore
|
|
' Log(fecha)
|
|
Dim OrigFormat As String = DateTime.DateFormat 'save orig date format
|
|
DateTime.DateFormat="yyMMddHHmmss"
|
|
Dim nuevaFecha As String=DateTime.Date(fecha)
|
|
DateTime.DateFormat=OrigFormat 'return to orig date format
|
|
' Log(nuevaFecha)
|
|
Return nuevaFecha
|
|
End Sub
|
|
|
|
'Convierte una fecha al formato yyMMddHHmmssSSS -- con milisegundos
|
|
Sub fechaKMTms(fecha As String) As String 'ignore
|
|
' Log(fecha)
|
|
Dim OrigFormat As String = DateTime.DateFormat 'save orig date format
|
|
DateTime.DateFormat="yyMMddHHmmssSSS"
|
|
Dim nuevaFecha As String=DateTime.Date(fecha)
|
|
DateTime.DateFormat=OrigFormat 'return to orig date format
|
|
' Log(nuevaFecha)
|
|
Return nuevaFecha
|
|
End Sub
|
|
|
|
'Convierte una fecha en formato YYMMDDHHMMSS a Ticks
|
|
Sub fechaKMT2Ticks(fKMT As String) As Long 'ignore
|
|
Try
|
|
If fKMT.Length = 12 Then
|
|
Private parteFecha As String = fKMT.SubString2(0,6)
|
|
Private parteHora As String = fKMT.SubString(6)
|
|
Private OrigFormat As String = DateTime.DateFormat 'save original date format
|
|
DateTime.DateFormat="yymmdd"
|
|
DateTime.TimeFormat="HHmmss"
|
|
Private ticks As Long = DateTime.DateTimeParse(parteFecha,parteHora)
|
|
DateTime.DateFormat=OrigFormat 'return to original date format
|
|
Return ticks
|
|
Else
|
|
If Starter.logger Then Log("Formato de fecha incorrecto, debe de ser 'YYMMDDHHMMSS', no '"&fKMT&"' largo="&fKMT.Length)
|
|
Return 0
|
|
End If
|
|
Catch
|
|
Log("FLP-fechaKMT2Ticks Error -> " & LastException)
|
|
If Starter.logger Then LogColor($"Fecha dada: ${fKMT}, Parte Fecha: ${parteFecha}, Parte Hora: ${parteHora}"$, Colors.Red)
|
|
Return 0
|
|
End Try
|
|
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 mandaLocAServer( id As String)
|
|
Starter.lastLocUpdate = DateTime.Now
|
|
If Not(IsPaused(Main)) Then CallSubDelayed(Main, "actualizaLabelUU")
|
|
Try
|
|
If Starter.IsNetAvailable Then
|
|
' Traemos las ubicaciones de RUTA_GPS que no estan ENVIADAS.
|
|
Private g0 As ResultSet = gps_hist.ExecQuery($"select * from RUTA_GPS where ifNull(ENVIADO,'0') = '0'"$)
|
|
Do While g0.NextRow
|
|
Starter.cmd.Initialize
|
|
Starter.cmd.Name = "borraDatos"
|
|
Starter.cmd.Parameters = Array As Object(g0.GetString("FECHA"), id)
|
|
If Starter.logger Then LogColor($">>>> Borramos loc de server: ${g0.GetString("FECHA")}, ${id}"$, Colors.Blue)
|
|
' Borramos de web la ubicacion, para despues en JobDone volverla a insertar, esto es porque si ya existe en web, causa un error por indices unicos y no se actualiza nada!
|
|
Starter.reqManager.ExecuteCommand(Starter.cmd,$"borraDatos_${g0.GetString("FECHA")}"$)
|
|
Loop
|
|
g0.close
|
|
End If
|
|
' Sleep(10000)
|
|
' Log($"PAUSAR_ENVIO: ${Starter.pausarEnvio}, IS_NET_AVAILABLE: ${Starter.IsNetAvailable}"$)
|
|
' If Not(Starter.pausarEnvio) And Starter.IsNetAvailable Then
|
|
' Private g As ResultSet = gps_hist.ExecQuery($"select * from RUTA_GPS where ifNull(ENVIADO,'0') = '0'"$)
|
|
' Do While g.NextRow
|
|
' Starter.pausarEnvio = True
|
|
' Starter.Timer2.Enabled = False
|
|
' Starter.Timer2.Interval = Starter.T2Interval
|
|
' Starter.Timer2.Enabled = True
|
|
' LogColor("PAUSAR ENVIO TRUE", Colors.Red)
|
|
' Starter.cmd.Initialize
|
|
' Starter.cmd.Name = "guardaDatos"
|
|
'' Log($"Time: ${g.GetString("TIME")}, Acc: ${g.GetString("ACC")}, Enviado: ${g.GetString("ENVIADO")}"$)
|
|
' Starter.cmd.Parameters = Array As Object(g.GetString("FECHA"), id, g.GetString("FECHA"), $"${g.GetString("LAT")},${g.GetString("LON")},${g.GetString("ACC")},True,${g.GetString("SPEED")},True"$, "Coords")
|
|
' If Starter.logger Then
|
|
' If Starter.logger Then LogColor($">>>> Mandamos loc a server: ${g.GetString("LAT")},${g.GetString("LON")},${g.GetString("ACC")},True,${g.GetString("SPEED")},True"$, Colors.Blue)
|
|
' End If
|
|
' Starter.reqManager.ExecuteCommand(Starter.cmd,$"guardaDatos_${g.GetString("FECHA")}"$)
|
|
' Loop
|
|
' g.close
|
|
' End If
|
|
Catch
|
|
Log(LastException)
|
|
End Try
|
|
End Sub
|
|
|
|
'Manda la ubicacion al servidor de BD y a FirebaseMessage.
|
|
Sub mandaLoc2(loc As Location, id As String) 'ignore
|
|
Try
|
|
Private minsTranscurridosLoc As String = ticksAMins(loc.time - traeVar("locAntTime", 0)) 'Minutos transcurridos desde la ultima ubicacion ACTUALIZADA.
|
|
Private minsTranscurridos As String = ticksAMins(DateTime.Now - traeUltimaUbicacionGuardada.Time) 'Minutos transcurridos desde la ultima ubicacion guardada.
|
|
Dim el_texto As String = ""
|
|
If Starter.logger Then LogColor("Guardada: " & minsTranscurridos & " mins., Actualizada: " & minsTranscurridosLoc & " mins.", Colors.green)
|
|
' If traeVar("solicitudFM", 0) = 1 Or minsTranscurridos >= 3 Or minsTranscurridosLoc >= 3 Then ' Para que no mande mensajes constantes, minimo 1 minuto entre mensajes.
|
|
' CallSubDelayed(Tracker,"CreateLocationRequest")
|
|
Tracker.flp.RequestLocationUpdates(Tracker.locReqNormal)
|
|
'Solo mandamos la ubicacion si la precision es dentro de XX mts
|
|
el_texto = $"LocChange - Coords NO enviadas (Acc:${loc.Accuracy})."$
|
|
If loc.Accuracy < 50 Then
|
|
If Starter.logger Then LogColor("Guardamos y enviamos ubicacion.", Colors.green)
|
|
guardaInfoEnBD(loc) 'Escribimos coordenadas y fecha a una bd
|
|
mandaLocAServer(id)
|
|
' FirebaseMessaging.locRequest = "Activa"
|
|
' CallSubDelayed2(FirebaseMessaging, "mandaLocFM", loc)
|
|
el_texto = $"LocChange - Coords enviadas (Acc:${loc.Accuracy})."$
|
|
End If
|
|
bitacora($"${el_texto}"$)
|
|
actualizaVar("solicitudFM", 0)
|
|
' ToastMessageShow("LocChanged MORE than a min.", False)
|
|
' Else
|
|
'' ToastMessageShow("Locatin changed but less than a min!.", False)
|
|
' End If
|
|
actualizaVar("locAntTime", loc.time)
|
|
Catch
|
|
CreateNotification(LastException)
|
|
Log(LastException)
|
|
End Try
|
|
End Sub
|
|
|
|
Sub ConvertMillisecondsToString(t As Long) As String 'ignore
|
|
Dim hours, minutes, seconds As Int
|
|
hours = t / DateTime.TicksPerHour
|
|
minutes = (t Mod DateTime.TicksPerHour) / DateTime.TicksPerMinute
|
|
seconds = (t Mod DateTime.TicksPerMinute) / DateTime.TicksPerSecond
|
|
Return $"$1.0{hours}:$2.0{minutes}:$2.0{seconds}"$
|
|
End Sub
|
|
|
|
'Convierte ticks a minutos.
|
|
Sub ticksAMins(ts As Long) As Long 'ignore
|
|
Private m As Long = ((ts/1000)/60)
|
|
Return m
|
|
End Sub
|
|
|
|
Sub bitacora(texto As String) 'ignore
|
|
revisaBD
|
|
' Log(fechaNormal(DateTime.now))
|
|
Try
|
|
gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${Starter.devModel}', '${texto}', '${fechaNormal(DateTime.now)}')"$)
|
|
Catch
|
|
Log(LastException)
|
|
End Try
|
|
End Sub
|
|
|
|
'Borramos renglones extra de la tabla de errores
|
|
Sub borraArribaDeXXXBitacora(limite As Int) '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 ${limite})"$)
|
|
gps_hist.ExecNonQuery("vacuum;")
|
|
' if starter.logger then Log("Borramos mas de 100 de errorLog")
|
|
End Sub
|
|
|
|
'Borramos renglones extra de la tabla RUTA_GPS
|
|
Sub borraArribaDeXXXUbicaciones(limite As Int) 'ignore
|
|
If Starter.logger Then LogColor("Recortamos la tabla RUTA_GPS, limite de 10,000", Colors.Magenta)
|
|
gps_hist.ExecNonQuery($"DELETE FROM RUTA_GPS WHERE fecha NOT in (SELECT fecha FROM RUTA_GPS ORDER BY fecha desc LIMIT ${limite})"$)
|
|
gps_hist.ExecNonQuery("vacuum;")
|
|
' if starter.logger then Log("Borramos mas de 100 de errorLog")
|
|
End Sub
|
|
|
|
'Regresa la ultima ubicacion guardada o una ubicacion sin inicializar si no encuentra nada.
|
|
Sub traeUltimaUbicacionGuardada As Location 'ignore
|
|
Private loc As Location
|
|
loc.Initialize
|
|
Private c As Cursor = gps_hist.ExecQuery($"select FECHA, LAT, LON, ACC, TIME, ifnull(BEARING, 0) as BEARING, ifnull(BEARING_DIFF, 0) as BEARING_DIFF, ifnull(DISTANCE_DIFF, 0) as DISTANCE_DIFF, ifnull(SPEED, 0) as SPEED, ifnull(ENVIADO, 0) as ENVIADO from RUTA_GPS order by fecha desc limit 1"$)
|
|
If c.RowCount > 0 Then
|
|
c.Position = 0
|
|
loc.Latitude = c.GetString("LAT")
|
|
loc.Longitude = c.GetString("LON")
|
|
loc.Bearing = c.GetString("BEARING")
|
|
loc.Speed = c.GetString("SPEED")
|
|
loc.Accuracy = 0
|
|
If c.GetString("ACC") <> Null Then loc.Accuracy = c.GetString("ACC")
|
|
loc.Time = 0
|
|
If c.GetString("TIME") <> Null Then loc.Time = c.GetString("TIME")
|
|
End If
|
|
c.Close
|
|
Return loc
|
|
End Sub
|
|
|
|
'Busca la ultima ubicacion guardada en la table GPS_HIST, y dependiendo del tiempo transcurrido hace lo siguiente:
|
|
' - Mas de 10 minutos -> Pide actualización de ubicacion.
|
|
' - Mas de 20 minutos -> Apaga y prende el servicio de FLP.
|
|
' - Mas de 30 minutos -> Reinicia la aplicación.
|
|
Sub revisaYguardaUUC
|
|
Private ultimaLoc As Location = traeUltimaUbicacionGuardada
|
|
If ultimaLoc.IsInitialized Then
|
|
Starter.UUC = ultimaLoc
|
|
Private minsTranscurridos As String = ticksAMins(DateTime.Now - ultimaLoc.Time) 'Minutos transcurridos desde la ultima ubicacion guardada.
|
|
If Starter.logger Then Log($"Ultima ubicacion guardada hace ${minsTranscurridos} mins."$)
|
|
If minsTranscurridos > 10 And minsTranscurridos < 20 Then
|
|
bitacora("Mas de 10 mins - REQ-UPDATE")
|
|
LogColor($"Ubicacion vieja (mas de 10 mins.)"$, Colors.Red)
|
|
LogColor("Pedimos actualizacion!", Colors.blue)
|
|
If Tracker.flp.IsInitialized And Tracker.flp.IsConnected And Tracker.locReqSmall.IsInitialized Then
|
|
bitacora("REQ-UPDATE") : LogColor("REQ-UPDATE", Colors.magenta)
|
|
Try
|
|
Tracker.flp.RequestLocationUpdates(Tracker.locReqSmall)
|
|
Catch
|
|
Log(LastException)
|
|
End Try
|
|
Else
|
|
bitacora("TRACKER APAGADO - RESTART-TRACKER") : LogColor("RESTART-TRACKER", Colors.magenta)
|
|
StopService(Tracker)
|
|
Sleep(5000)
|
|
StartService(Tracker)
|
|
End If
|
|
else if minsTranscurridos >= 20 And minsTranscurridos < 30 Then
|
|
LogColor("RESTART-TRACKER", Colors.red)
|
|
bitacora("Mas de 20 mins - RESTART-TRACKER")
|
|
' bitacora(Tracker.flp.SuspendedCause)
|
|
StopService(Tracker)
|
|
Sleep(5000)
|
|
StartService(Tracker)
|
|
else If minsTranscurridos >= 30 Then
|
|
If Tracker.flp.IsInitialized And Tracker.flp.IsConnected Then LogColor($"FLP.Connected: ${Tracker.flp.IsConnected}"$, Colors.Red)
|
|
If Tracker.flp.IsInitialized And Not(Tracker.flp.IsConnecting) Then 'Si NO esta en proceso de conectarse ...
|
|
LogColor("RESTART-APP", Colors.red)
|
|
bitacora("Mas de 30 mins - RESTART-APP")
|
|
' bitacora(Tracker.flp.SuspendedCause) 'ignore
|
|
Starter.UUC.Time = DateTime.Now
|
|
guardaInfoEnBD(Starter.UUC) 'Guardamos la ultima ubicacion con la hora actual, para que no se reinicie la app si no consigue una ubicacion nueva.
|
|
' Sleep(1000)
|
|
StopService(Tracker)
|
|
Sleep(5000)
|
|
StartService(Tracker)
|
|
CallSubDelayed(Tracker, "StartFLP")
|
|
' ExitApplication
|
|
End If
|
|
End If
|
|
' LogColor($"Ultima loc: ${Subs.fechaNormal(ultimaLoc.Time)}"$, Colors.blue)
|
|
End If
|
|
End Sub
|
|
|
|
Sub actualizaVar(nombre As String, valor As String)
|
|
gps_hist.ExecNonQuery($"delete from CAT_VARIABLES where NOMBRE = '${nombre}'"$)
|
|
gps_hist.ExecNonQuery($"insert into CAT_VARIABLES (NOMBRE, VALOR) values ('${nombre}', '${valor}')"$)
|
|
End Sub
|
|
|
|
'Regresa el valor desde CAT_VARIABLES o del default espacificado en DEFAULT
|
|
Sub traeVar(nombre As String, default As String) As String
|
|
Private v As String = default
|
|
Private c As Cursor = gps_hist.ExecQuery2("select VALOR from CAT_VARIABLES WHERE NOMBRE = ?", Array As String (nombre))
|
|
If c.RowCount > 0 Then
|
|
c.Position = 0
|
|
v = c.GetString("VALOR")
|
|
End If
|
|
Return v
|
|
End Sub
|
|
|
|
Sub agregaColumna(tabla As String, columna As String, tipo As String) 'ignore
|
|
Try 'Intentamos usar "pragma_table_info" para revisar si existe la columna en la tabla
|
|
Private c As Cursor = gps_hist.ExecQuery($"SELECT COUNT(*) AS fCol FROM pragma_table_info('${tabla}') WHERE name='${columna}'"$)
|
|
c.Position = 0
|
|
If c.GetString("fCol") = 0 Then 'Si no esta la columna la agregamos
|
|
gps_hist.ExecNonQuery($"ALTER TABLE ${tabla} ADD COLUMN ${columna} ${tipo}"$)
|
|
Log($"Columna "${columna} ${tipo}", agregada a "${tabla}"."$)
|
|
End If
|
|
' Log(1)
|
|
Catch 'Si no funciona "pragma_table_info" lo hacemos con try/catch
|
|
Try
|
|
gps_hist.ExecNonQuery($"ALTER TABLE ${tabla} ADD COLUMN ${columna} ${tipo}"$)
|
|
Log($"Columna "${columna} ${tipo}", agregada a "${tabla}".."$)
|
|
Catch
|
|
Log(LastException)
|
|
End Try
|
|
Log(2)
|
|
End Try
|
|
End Sub
|