mirror of
https://github.com/cheveguerra/FLP_2.0.git
synced 2026-04-17 19:36:42 +00:00
348 lines
14 KiB
QBasic
348 lines
14 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
|
|
revisaBD
|
|
If Starter.logger Then Log($"Guardamos ubicacion en db (${loc.Latitude},${loc.Longitude})"$)
|
|
gps_hist.ExecNonQuery2("INSERT INTO RUTA_GPS(fecha, lat, lon, acc, time) VALUES (?,?,?,?,?)", Array As Object (fechaKMT(loc.time),loc.Latitude,loc.Longitude, loc.Accuracy, loc.time))
|
|
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")
|
|
Main.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)")
|
|
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 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(loc As Location, id As String)
|
|
Starter.lastLocUpdate = DateTime.Now
|
|
If Not(IsPaused(Main)) Then CallSubDelayed(Main, "actualizaLabelUU")
|
|
Starter.cmd.Initialize
|
|
Starter.cmd.Name = "guardaDatos"
|
|
Starter.cmd.Parameters = Array As Object(fechaKMT(DateTime.Now), id, fechaKMT(DateTime.Now), $"${loc.Latitude},${loc.Longitude},${loc.Accuracy},${loc.AccuracyValid},${loc.Speed},${loc.SpeedValid}"$, "Coords")
|
|
' If Starter.logger Then
|
|
If Starter.logger Then Log($">>>> Mandamos loc a server: ${fechaKMT(DateTime.Now)}|${id}|${fechaKMT(DateTime.Now)}|${loc.Latitude},${loc.Longitude}|Coords"$)
|
|
' End If
|
|
Starter.reqManager.ExecuteCommand(Starter.cmd,"guardaDatos")
|
|
End Sub
|
|
|
|
'Manda la ubicacion al servidor de BD y a FirebaseMessage.
|
|
Sub mandaLoc2(loc As Location, id As String) 'ignore
|
|
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)
|
|
mandaLocAServer(loc, id)
|
|
FirebaseMessaging.locRequest = "Activa"
|
|
CallSubDelayed2(FirebaseMessaging, "mandaLocFM", loc)
|
|
guardaInfoEnBD(loc)'Escribimos coordenadas y fecha a una bd
|
|
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)
|
|
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))
|
|
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 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
|
|
|
|
'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 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.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 actualzación de ubicacion.
|
|
' - Mas de 20 minutos -> Apaga y prende el servicio de FLP.
|
|
' - Mas de 30 minutos -> Reinicia la aplicación.
|
|
Sub revisaYmandaUUC
|
|
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 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 |