Cambio de puerto

This commit is contained in:
2023-11-07 18:59:47 -06:00
parent 68bac1707c
commit 9ed8905671
10 changed files with 508 additions and 140 deletions

253
FLP_2.0.b4a Normal file
View File

@@ -0,0 +1,253 @@
Build1=Default,flp2.chv.com
File1=gps_hist.db
File2=Layout.bal
FileGroup1=Default Group
FileGroup2=Default Group
Group=Default Group
Library1=administrator
Library10=mlwifi400
Library11=okhttputils2
Library12=phone
Library13=randomaccessfile
Library14=reflection
Library15=replyauto
Library16=runtimepermissions
Library17=sql
Library2=byteconverter
Library3=compressstrings
Library4=core
Library5=firebaseanalytics
Library6=firebasenotifications
Library7=fusedlocationprovider
Library8=gps
Library9=json
ManifestCode='This code will be applied to the manifest file during compilation.~\n~'You do not need to modify it in most cases.~\n~'See this link for for more information: https://www.b4x.com/forum/showthread.php?p=78136~\n~AddManifestText(~\n~<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="29"/>~\n~<supports-screens android:largeScreens="true" ~\n~ android:normalScreens="true" ~\n~ android:smallScreens="true" ~\n~ android:anyDensity="true"/>)~\n~SetApplicationAttribute(android:icon, "@drawable/icon")~\n~SetApplicationAttribute(android:label, "$LABEL$")~\n~CreateResourceFromFile(Macro, Themes.LightTheme)~\n~'End of default text.~\n~AddPermission(android.permission.ACCESS_FINE_LOCATION)~\n~AddPermission(android.permission.WRITE_EXTERNAL_STORAGE)~\n~CreateResourceFromFile(Macro, FirebaseAnalytics.GooglePlayBase)~\n~CreateResourceFromFile(Macro, FirebaseAnalytics.Firebase)~\n~CreateResourceFromFile(Macro, FirebaseAnalytics.FirebaseAnalytics)~\n~CreateResourceFromFile(Macro, FirebaseNotifications.FirebaseNotifications)~\n~SetServiceAttribute(Tracker, android:foregroundServiceType, "location")~\n~SetApplicationAttribute(android:usesCleartextTraffic, "true")~\n~AddApplicationText(<receiver android:name="anywheresoftware.b4a.objects.AdminReceiver2"~\n~ android:permission="android.permission.BIND_DEVICE_ADMIN">~\n~ <meta-data android:name="android.app.device_admin"~\n~ android:resource="@xml/device_admin" />~\n~ <intent-filter>~\n~ <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />~\n~ </intent-filter>~\n~</receiver>)~\n~~\n~CreateResource(xml, device_admin.xml,~\n~<device-admin xmlns:android="http://schemas.android.com/apk/res/android">~\n~ <uses-policies>~\n~ <limit-password />~\n~ <reset-password />~\n~ <force-lock />~\n~ </uses-policies>~\n~</device-admin>~\n~)~\n~AddPermission(android.permission.SEND_SMS)~\n~AddPermission(android.permission.RECEIVE_SMS)~\n~AddPermission(android.permission.READ_PHONE_STATE)~\n~AddPermission(android.permission.READ_CALL_LOG)~\n~AddApplicationText(~\n~<service android:name="b4a.jsaplication.com.br.ReplyAuto"~\n~ android:label="Mariana" android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">~\n~ <intent-filter><action android:name="android.service.notification.NotificationListenerService" /></intent-filter>~\n~ </service>)~\n~ ~\n~AddPermission(android.permission.RECEIVE_BOOT_COMPLETED)~\n~AddReceiverText(R_Test, <intent-filter>~\n~<action android:name="android.intent.action.BOOT_COMPLETED"/>~\n~</intent-filter>)
Module1=DBRequestManager
Module2=FirebaseMessaging
Module3=Mods
Module4=NotificationService
Module5=R_Test
Module6=Starter
Module7=Subs
Module8=Tracker
NumberOfFiles=2
NumberOfLibraries=17
NumberOfModules=8
Version=12.5
@EndOfDesignText@
#Region Project Attributes
#ApplicationLabel: FLP 2.0
#VersionCode: 1
#VersionName: 3.10.01
'SupportedOrientations possible values: unspecified, landscape or portrait.
#SupportedOrientations: unspecified
#CanInstallToExternalStorage: False
' #AdditionalJar: com.android.support:support-v4
#AdditionalJar: com.google.android.gms:play-services-location
#BridgeLogger:True
'###########################################################################################################
'###################### PULL #############################################################
'Ctrl + click ide://run?file=%WINDIR%\System32\cmd.exe&Args=/c&Args=git&Args=pull
'###########################################################################################################
'###################### PUSH #############################################################
'Ctrl + click ide://run?file=%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe&Args=github&Args=..\..\
'###########################################################################################################
'###################### PUSH TORTOISE GIT #########################################################
'Ctrl + click ide://run?file=%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe&Args=TortoiseGitProc&Args=/command:commit&Args=/path:"./../"&Args=/closeonend:2
'###########################################################################################################
#End Region
#Region Activity Attributes
#FullScreen: False
#IncludeTitle: True
#End Region
Sub Process_Globals
'These global variables will be declared once when the application starts.
'These variables can be accessed from all modules.
Dim wifi As MLwifi
Dim wifiS As MLScan
Public manager As AdminManager
' Dim ruta As String
Dim fechaRuta As String
Dim laUbicacion As Location
End Sub
Sub Globals
'These global variables will be redeclared each time the activity is created.
Private b_pong As Button
Private et_id As EditText
Private b_guardarId As Button
Private l_coords As Label
Dim l_lastUpdate As Label
Private l_id As Label
' Private b_flpConnect As Button
Private b_exit As Button
End Sub
Sub Activity_Create(FirstTime As Boolean)
Activity.LoadLayout("Layout")
' ruta = File.DirInternal
Subs.getPhnId
et_id.Text = Starter.devModel.trim
getSSID
b_pong.Left = Round(Activity.Width/2)-(b_pong.Width/2)
' b_flpConnect.Left = Round(Activity.Width/2)-(b_flpConnect.Width/2)
b_exit.Left = Round(Activity.Width/2)-(b_exit.Width/2)
l_id.Left = (Activity.Width / 2) - (l_id.Width / 2)
l_lastUpdate.Left = (Activity.Width / 2) - (l_lastUpdate.Width / 2)
b_guardarId.Left = (Activity.Width / 2) - (b_guardarId.Width / 2)
et_id.Left = (Activity.Width / 2) - (et_id.Width / 2)
End Sub
Sub Activity_Resume
chkPermisosUbicacion 'Permisos de ubicacion para Tracker
chkPermisosAlmacenamientoExterno
Subs.getPhnId
et_id.Text = Starter.devModel.Trim
getSSID
getAdminRights
l_lastUpdate.Text = Subs.fechaKMT(Starter.lastLocUpdate)
' ruta = File.DirInternal
If Not(CheckNotificationAccess) Then
Msgbox2Async($"Se necesita acceso a las notificaciones, haga clic en "Aceptar" y en la siguiente pantalla permita el acceso a la aplicación "${Application.LabelName}"."$, "Permisos necesarios", "Aceptar", "Cancelar", "", Null, True)
Wait For Msgbox_Result (resultado As Int)
If resultado = DialogResponse.POSITIVE Then
Dim In As Intent
In.Initialize("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS", "")
StartActivity(In)
End If
End If
ponCoords
End Sub
Sub Activity_Pause (UserClosed As Boolean)
End Sub
Sub b_pong_Click
CallSubDelayed(Tracker, "StartFLP")
If laUbicacion.IsInitialized Then Subs.mandaLocAServer(laUbicacion, Starter.devModel.Trim)
Dim params As Map = CreateMap("topic": FirebaseMessaging.Sprvsr,"title":"Prueba Trckr", "body":"Prueba Trckr", "d":Starter.devModel, "t":"pong")
CallSubDelayed2(FirebaseMessaging, "SendMessage",params)
If Starter.logger Then Log("Start wifi scan")
wifiS.startscan("WiFi", True)
Wait For WiFi_ScanDone (Results() As String, Count As Int)
End Sub
Sub b_pong_LongClick
' copiaDB
CallSubDelayed(Tracker, "StartFLP")
If laUbicacion.IsInitialized Then Subs.mandaLocAServer(laUbicacion, Starter.devModel.Trim)
Dim params As Map = CreateMap("topic": FirebaseMessaging.Sprvsr,"title":"Prueba Trckr", "body":l_coords.Text, "d":Starter.devModel, "t":"au")
CallSubDelayed2(FirebaseMessaging, "SendMessage",params)
If Starter.logger Then Log("Start wifi scan")
wifiS.startscan("WiFi", True)
Wait For WiFi_ScanDone (Results() As String, Count As Int)
End Sub
Sub chkPermisosAlmacenamientoExterno
Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
If Result Then
' If Starter.logger Then Log("Permisos de almacenamiento externo OK")
Else
' ToastMessageShow("SIN permisos de almacenamiento externo", True)
End If
End Sub
Sub chkPermisosUbicacion
' If Starter.logger Then Log("Revisamos permisos de ubicación.")
Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION)
Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
If Result Then
StartService(Tracker)
If Starter.logger Then Log("Start Tracker")
Else
' ToastMessageShow("SIN permisos de ubicacion", True)
End If
End Sub
Sub getSSID
If wifi.isWifiConnected Then
Subs.ssid = wifi.WifiSSID
End If
End Sub
Sub getAdminRights
If manager.Enabled = False Then
manager.Enable("Please enable in order to get access to the secured server.")
End If
End Sub
'Sub wifiScanned_ScanDone
' Log("//////////////////////////////wifi_conected_result")
' ToastMessageShow("Wifi_ConnectionResult",True)
' If wifi.isWifiConnected Then
' ssid = wifi.WifiSSID
' End If
'End Sub
Sub copiaDB 'ignore
' Log("ruta="&ruta)
' Log("File.DirInternal="&File.DirInternal)
' Log("File.DirRootExternal="&File.DirRootExternal)
' Log("File.DirDefaultExternal="&File.DirDefaultExternal)
' Log(Starter.rp.GetSafeDirDefaultExternal(""))
' Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
' Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
' If Result Then
' If Starter.logger Then Log("Tenemos permisos de escritura.")
' File.Copy(File.DirInternal , "gps_hist.db", File.DirDefaultExternal, "gps_hist.db")
' If Starter.logger Then Log($"DB escrita a ${File.DirDefaultExternal}"$)
' ToastMessageShow($"DB escrita a ${File.DirDefaultExternal}"$, True)
' End If
End Sub
Private Sub b_guardarId_Click
If et_id.Text.Length > 2 Then 'Si tenemos valor para ID
File.WriteString(File.DirInternal, "phnId.txt", et_id.Text.trim) 'Sobreescribimos archivo IdPersonal.txt con ID
Starter.devModel = et_id.Text.Trim
If Starter.logger Then Log("Tenemos ID: "& et_id.Text.Trim & " "&File.DirInternal&"/phnId.txt sobreescrito")
Else If et_id.Text.Length < 3 Then ' Si no tenemos valor, lo leemos de IdPersonal.txt
Dim s As String = File.ReadString(File.DirInternal, "phnId.txt")
Starter.devModel = s
If Starter.logger Then Log("Leemos id de "&File.DirInternal&"/phnId.txt")
et_id.Text = Starter.devModel.Trim
If Starter.logger Then Log(Starter.devModel.Trim)
End If
If laUbicacion.IsInitialized Then Subs.mandaLocAServer(laUbicacion, Starter.devModel.Trim)
End Sub
Sub ponCoords
l_coords.left = (Activity.Width/2) - (l_coords.Width/2)
l_coords.Text = $"${Starter.UUC.Latitude},${Starter.UUC.Longitude}"$
End Sub
'Revisa si la aplicación tiene permiso para acceder a las notificaciones.
Sub CheckNotificationAccess As Boolean
Dim ph As Phone
Dim nstr, pstr As String
Dim r As Reflector
pstr = r.GetStaticField("anywheresoftware.b4a.BA", "packageName")
nstr = ph.GetSettings("enabled_notification_listeners")
Return nstr.Contains(pstr)
End Sub
Sub actualizaLabelUU
l_lastUpdate.Text = Subs.fechaKMT(Starter.lastLocUpdate)
End Sub
'Private Sub b_flpConnect_Click
' Log("Conectamos a FLP")
' CallSubDelayed(Tracker, "flpReConnect")
'End Sub
Private Sub b_exit_Click
' CallSubDelayed(Tracker, "flpReConnect")
Starter.restartTracker
End Sub
Sub b_exit_LongClick
ExitApplication
End Sub

30
FLP_2.0.b4a.meta Normal file
View File

@@ -0,0 +1,30 @@
ModuleBookmarks0=
ModuleBookmarks1=
ModuleBookmarks2=
ModuleBookmarks3=
ModuleBookmarks4=
ModuleBookmarks5=
ModuleBookmarks6=
ModuleBookmarks7=
ModuleBookmarks8=
ModuleBreakpoints0=
ModuleBreakpoints1=
ModuleBreakpoints2=
ModuleBreakpoints3=
ModuleBreakpoints4=
ModuleBreakpoints5=
ModuleBreakpoints6=
ModuleBreakpoints7=
ModuleBreakpoints8=
ModuleClosedNodes0=12,13
ModuleClosedNodes1=
ModuleClosedNodes2=5,6,7,9,10
ModuleClosedNodes3=1
ModuleClosedNodes4=
ModuleClosedNodes5=
ModuleClosedNodes6=
ModuleClosedNodes7=2,3,4,5,6,7,9,10,11,13,14,15,16,17,19,20,22
ModuleClosedNodes8=8,10,11,12
NavigationStack=Tracker,flp_ConnectionSuccess,78,3,Tracker,flp_ConnectionFailed,83,1,NotificationService,NotiMon_NotificationPosted,72,0,Tracker,flp_ConnectionSuspended,173,0,Starter,Timer1_Tick,47,2,Subs,revisaYmandaUUC,279,6,Starter,Service_Start,30,0,Subs,revisaBD,130,0,Subs,traeUltimaUbicacionGuardada,243,5,Subs,bitacora,222,0
SelectedBuild=0
VisibleModules=6,2,8,3,7,4,5

Binary file not shown.

View File

@@ -46,7 +46,7 @@ Sub Process_Globals
End Sub
Sub Service_Create
Starter.ruta = File.DirInternal
Subs.revisaBD
fm.Initialize("fm") 'Inicializamos FirebaseMessaging
Subs.getPhnId
pe.Initialize("pe") 'Para obtener la bateria
@@ -67,8 +67,6 @@ End Sub
Sub Service_Start (StartingIntent As Intent)
Subs.getPhnId
Subs.gps_hist.Initialize(Starter.ruta,"gps_hist.db", True)
Subs.gps_hist.ExecNonQuery("CREATE TABLE IF NOT EXISTS RUTA_GPS(FECHA INTEGER, LAT TEXT, LON TEXT)")
If StartingIntent.IsInitialized Then fm.HandleIntent(StartingIntent)
Sleep(0)
Service.StopAutomaticForeground 'remove if not using B4A v8+.
@@ -86,7 +84,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)
mandaLocFM(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,11 +154,9 @@ Sub SendMessage(params As Map)
If Starter.logger Then Log("Mandamos mensaje: " & m)
End Sub
Sub mandamosLoc(loc As Location)
Sub mandaLocFM(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
If Starter.logger Then LogColor("Iniciamos mandaLocFM ("&coords&")", Colors.Magenta)
Dim t As String
If locRequest="Activa" Then
If au = 1 Then

View File

@@ -56,6 +56,7 @@ Sub Service_Create
#if not(DEBUG)
logger = False
#end if
Subs.revisaBD
' If logger Then Log("**************** Iniciamos Monitor Keymon ***********************")
End Sub
@@ -72,20 +73,7 @@ Sub Service_Destroy
End Sub
Sub NotiMon_NotificationPosted (SBN As StatusBarNotification)
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.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
Subs.revisaYmandaUUC
If Starter.logger Then LogColor(SBN.PackageName & " - " & SBN.Message, Colors.blue)
' Log("-= Notificacion recibida =-")
If SBN.PackageName = "com.whatsapp" Then
@@ -97,13 +85,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.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")
Subs.bitacora($"Recibimos notificación, pedimos actualización y mandamos UUC."$)
Tracker.flp.RequestLocationUpdates(Tracker.locReqSmall)
Sleep(2000)
Private ultimaLoc As Location = Subs.traeUltimaUbicacionGuardada
Subs.mandaLoc2(ultimaLoc, Starter.devModel)
End If
End If
End If

18
R_Test.bas Normal file
View File

@@ -0,0 +1,18 @@
B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Receiver
Version=12.5
@EndOfDesignText@
Sub Process_Globals
End Sub
'Called when an intent is received.
'Do not assume that anything else, including the starter service, has run before this method.
Private Sub Receiver_Receive (FirstTime As Boolean, StartingIntent As Intent)
Log("RECEIVER RECEIVED - BOOT COMPLETED")
Subs.revisaBD
Subs.bitacora("RECEIVER BOOT COMPLETED")
End Sub

View File

@@ -14,63 +14,44 @@ Sub Process_Globals
'These variables can be accessed from all modules.
Public rp As RuntimePermissions 'Para obtener permisos android 6+
Public FLP As FusedLocationProvider 'Para Tracker
Dim ruta As String
Dim reqManager As DBRequestManager
Dim cmd As DBCommand
Dim Timer1 As Timer
Dim interval As Int = 600 '600 segs (10 mins)
Dim interval As Int = 1800 '1800 segs (30 mins)
Dim UUC As Location
Dim run As Int = 0 'ignore
Dim devModel As String
Dim lastLocUpdate As String = 0
Dim logger As Boolean = True
' Dim FLPStatus As String
End Sub
Sub Service_Create
'This is the program entry point.
'This is a good place to load resources that are not specific to a single activity.
ruta = File.DirInternal 'Ruta de la base de datos por defecto.
If File.ExternalWritable Then ruta = rp.GetSafeDirDefaultExternal("") 'Si podemos escribir a la tarjeta, cambiamos la ruta.
If Not(File.Exists(ruta, "gps_hist.db")) Then File.Copy(File.DirAssets, "gps_hist.db", ruta, "gps_hist.db") 'Si no existe el archivo de la base de datos, lo copiamos.
If Subs.gps_hist.IsInitialized = False Then Subs.gps_hist.Initialize(ruta, "gps_hist.db", True)
Subs.gps_hist.ExecNonQuery("CREATE TABLE IF NOT EXISTS BITACORA(RUTA TEXT, TEXTO TEXT, FECHA TEXT)")
If logger Then Log(ruta)
Subs.revisaBD
CallSubDelayed(FirebaseMessaging, "SubscribeToTopics") 'Para FirebaseMessaging
End Sub
Sub Service_Start (StartingIntent As Intent)
Service.StopAutomaticForeground 'Starter service can start in the foreground state in some edge cases.
' reqManager.Initialize(Me, "http://10.0.0.205:1782")
reqManager.Initialize(Me, "http://keymon.lat:1782")
reqManager.Initialize(Me, "http://keymon.lat:1781")
Timer1.Initialize("Timer1", interval * 1000)
Timer1.Enabled = True
UUC.Initialize
UUC.Accuracy = 1000
Subs.getPhnId
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)
StartServiceAt(Tracker, DateTime.Now + 30 * DateTime.TicksPerMinute, True)
#if RELEASE
logger = False
#end if
Subs.revisaYmandaUUC
End Sub
Private Sub Timer1_Tick
CallSubDelayed(Tracker, "StartFLP")
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.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
' Log("TIMER1: " & Timer1)
Subs.borraArribaDeXXXBitacora(3000)
End Sub
Sub Service_TaskRemoved
@@ -89,6 +70,7 @@ End Sub
Sub restartTracker
Log("Llamamos RESTART-TRACKER")
Subs.bitacora("Llamamos RESTART-TRACKER")
StopService(Tracker)
Sleep(1000)
StartService(Tracker)

145
Subs.bas
View File

@@ -34,9 +34,9 @@ Sub getPhnId 'Pone el valor de phn.Model en la variable global "devModel"
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")
' If Starter.logger Then Log("Escribimos phnId: "&elId&" a "&File.DirInternal&"/phnId.txt")
Starter.devModel = elId
If Starter.logger Then Log(Starter.devModel)
' If Starter.logger Then Log(Starter.devModel)
End Sub
Sub compress(str As String) As String ' Compresion
@@ -91,16 +91,16 @@ Sub guardaInfoEnArchivo(coords As String) 'Escribimos coordenadas y fecha a un a
out.Close
End Sub
Sub guardaInfoEnBD(coords As String) 'Escribimos coordenadas y fecha a una BD
If Starter.logger Then Log("Guardamos ubicacion en db (" & coords & ")")
Dim latlon() As String = Regex.Split(",", coords)
If gps_hist.IsInitialized = False Then gps_hist.Initialize(Starter.ruta, "gps_hist.db", True)
gps_hist.ExecNonQuery2("INSERT INTO RUTA_GPS(fecha, lat, lon) VALUES (?,?,?)", Array As Object (latlon(2),latlon(0),latlon(1)))
'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(Starter.ruta, "gps_hist.db", True)
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 = ""
@@ -131,11 +131,10 @@ Sub borramosArchivoGPS
End Sub
Sub revisaBD
' Starter.ruta = File.DirInternal
If File.Exists(Starter.ruta, "gps_hist.db") = False Then
File.Copy(File.DirAssets, "gps_hist.db", Starter.ruta, "gps_hist.db")
If Starter.logger Then Log("No existe gps_hist, copiamos gps_hist.db")
End If
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)
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)")
End Sub
Sub getSSID
@@ -155,6 +154,29 @@ Sub fechaKMT(fecha As String) As String 'ignore
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
Log("Formato de fecha incorrecto, debe de ser 'YYMMDDHHMMSS', no '"&fKMT&"' largo="&fKMT.Length)
Return 0
End If
Catch
Log(LastException)
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)
@@ -165,18 +187,6 @@ Sub fechaNormal(fecha As String) As String 'ignore
Return nuevaFecha
End Sub
'Sub dameUltimaUbicacionConocida(lastLocation As Location)
' Log(0)
' If Tracker.FLP.GetLastKnownLocation.IsInitialized Then 'Mandamos ultima ubicacion guardada
' Log("dameUltimaUbicacionConocida")
' If Tracker.FLP.GetLastKnownLocation.Accuracy < 30 And Tracker.FLP.GetLastKnownLocation.DistanceTo(lastLocation) > 50 Then
' Starter.UUC = Tracker.FLP.GetLastKnownLocation
' mandaLocAServer(Tracker.FLP.GetLastKnownLocation, Starter.devModel)
' Log($"UUC: ${Starter.UUC.Latitude},${Starter.UUC.Longitude}"$)
' End If
' End If
'End Sub
Sub mandaLocAServer(loc As Location, id As String)
Starter.lastLocUpdate = DateTime.Now
If Not(IsPaused(Main)) Then CallSubDelayed(Main, "actualizaLabelUU")
@@ -189,6 +199,14 @@ Sub mandaLocAServer(loc As Location, id As String)
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
mandaLocAServer(loc, id)
FirebaseMessaging.locRequest = "Activa"
CallSubDelayed2(FirebaseMessaging, "mandaLocFM", loc)
guardaInfoEnBD(loc)'Escribimos coordenadas y fecha a una bd
End Sub
Sub ConvertMillisecondsToString(t As Long) As String 'ignore
Dim hours, minutes, seconds As Int
hours = t / DateTime.TicksPerHour
@@ -197,15 +215,86 @@ Sub ConvertMillisecondsToString(t As Long) As String 'ignore
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 borraArribaDe10000Bitacora 'ignore
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 9999 )")
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
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
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.Initialize
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.
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.locReqSmall.IsInitialized Then
bitacora("REQ-UPDATE") : LogColor("REQ-UPDATE", Colors.magenta)
Tracker.flp.RequestLocationUpdates(Tracker.locReqSmall)
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)
ExitApplication
End If
End If
' LogColor($"Ultima loc: ${Subs.fechaNormal(ultimaLoc.Time)}"$, Colors.blue)
End If
End Sub

View File

@@ -36,30 +36,40 @@ Sub Process_Globals
Private nid As Int = 1
Private Tracking As Boolean
Private lock As PhoneWakeState
'Para FusedLocationProvider (2 lineas)
Public flp As FusedLocationProvider
Private flpStarted As Boolean
Dim minAccuracy As Int = 50
Dim killerCalled As Int = 0
Dim locReqSmall As LocationRequest
End Sub
Sub Service_Create
Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_NEVER 'we are handling it ourselves
'Para FusedLocationProvider (2 lineas)
Subs.revisaBD
flp.Initialize("flp")
flp.Connect
lock.PartialLock
StartFLP
If Starter.logger Then Log("FLP initialized")
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 Service_Start (StartingIntent As Intent)
locReqSmall = CreateLocationRequest2(1000, 0) 'ignore
Service.StopAutomaticForeground
Service.StartForeground(nid, Subs.CreateNotification("..."))
Track
StartServiceAt(Me, DateTime.Now + 60 * DateTime.TicksPerMinute, True)
Subs.bitacora($"Tracker - Service_Start"$)
End Sub
'Apagamos y prendemos sel servicio "Tracker" o reinicamos la aplicacion.
'killerCalled = 0 -> Apagamos y prendemos.
'killerCalled = 1 -> ExitApplication (se reinican todos los servicios).
Sub flpReConnect
Try
If killerCalled = 0 Then
killerCalled = 1
Subs.bitacora("Llamamos RESTART-TRACKER")
CallSubDelayed(Starter, "restartTracker")
Else
Subs.bitacora("Llamamos EXIT-APP")
@@ -72,25 +82,16 @@ End Sub
Sub flp_ConnectionSuccess
Log("FLP - Connected to location provider")
'FLP.GetLastKnownLocation
Subs.bitacora("FLP - Connection Success")
End Sub
Sub flp_ConnectionFailed(ConnectionResult1 As Int)
Log("Failed to connect to location provider")
End Sub
Sub Service_Start (StartingIntent As Intent)
'Para FusedLocationProvider (1 linea)
Service.StopAutomaticForeground
Service.StartForeground(nid, Subs.CreateNotification("..."))
Track
StartServiceAt(Me, DateTime.Now + 10 * DateTime.TicksPerMinute, True)
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)}')"$)
Subs.bitacora("FLP - Connection Failed")
End Sub
Public Sub Track
'Log("Track")
If Starter.logger Then Log("Track")
If Tracking Then Return 'Si ya estamos "rastreando" no hacemos nada (return)
If Starter.rp.Check(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION) = False Then
Log("No permission")
@@ -110,21 +111,17 @@ Public Sub StartFLP
cont = cont + 1
If cont > 70 Then
cont = 0
Log("Reiniciamos FLP")
flpReConnect
LogColor("Reiniciamos FLP", Colors.red)
killerCalled = 1 : flpReConnect
End If
Loop
' If flpStarted = False Then
' Log("RequestLocationUpdates")
' Starter.FLPStatus = "Searching" : LogColor("FLP Searching", Colors.blue)
flp.RequestLocationUpdates(CreateLocationRequest) 'Buscamos ubicacion
flpStarted = True
' End If
End Sub
Private Sub CreateLocationRequest As LocationRequest
Sub CreateLocationRequest As LocationRequest
' Log("CreateLocationRequest")
' Starter.FLPStatus = "Searching" : LogColor("FLP Searching", Colors.blue)
Dim lr As LocationRequest
lr.Initialize
lr.SetInterval(30000) 'Intervalo deseado para actualizaciones de ubicacion en milisegundos
@@ -134,21 +131,19 @@ Private Sub CreateLocationRequest As LocationRequest
Return lr
End Sub
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.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)
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}"$)
Sub CreateLocationRequest2(interval0 As Int, displacement0 As Int) As LocationRequest 'ignore
' Log("CreateLocationRequestSmall")
Dim lr As LocationRequest
lr.Initialize
lr.SetInterval(interval0) 'Intervalo deseado para actualizaciones de ubicacion en milisegundos
lr.SetFastestInterval(lr.GetInterval / 2) 'Intervalo minimo para actualizaciones de ubicacion
lr.SetSmallestDisplacement(displacement0) 'Solo registra cambio de ubicacion si es mayor a XX mts
lr.SetPriority(lr.Priority.PRIORITY_HIGH_ACCURACY)
Return lr
End Sub
Public Sub StopFLP
'Log("StopFLP")
If Starter.logger Then Log("StopFLP")
If flpStarted Then
flp.RemoveLocationUpdates 'Eliminamos todas las solicitudes de ubicacion
flpStarted = False
@@ -156,35 +151,39 @@ Public Sub StopFLP
End Sub
Sub flp_LocationChanged (Location1 As Location)
' Starter.FLPStatus = "Location changed" : LogColor("Location changed", Colors.blue)
LogColor($"Location Changed - Acc: ${Location1.Accuracy}"$, Colors.blue)
Dim el_texto As String = ""
Starter.UUC = Location1
If Not(Starter.Timer1.Enabled) Then
Starter.Timer1.Enabled = True
Log("FLP - Timer Enabled")
End If
flp.RequestLocationUpdates(CreateLocationRequest)
If Starter.logger Then LogColor("FLP_LocationChanged", Colors.Red)
' ToastMessageShow("FLP_LocationChanged", False)
Main.laUbicacion = Location1
' ToastMessageShow(coords, False)
' Log("Mandamos Ubicacion")
If Starter.logger Then Log(FirebaseMessaging.locRequest)
If Starter.logger Then Log(Location1)
If Starter.logger Then Log(Location1.Accuracy&" - "&Location1.AccuracyValid)
' solo mandamos la ubicacion si la precision es dentro de XX mts
el_texto = $"LocChange - Coords NO enviadas (Acc:${Location1.Accuracy})."$
'Solo mandamos la ubicacion si la precision es dentro de XX mts
If Location1.Accuracy < minAccuracy Then
Subs.mandaLocAServer(Location1, Starter.devModel)
FirebaseMessaging.locRequest = "Activa"
CallSubDelayed2(FirebaseMessaging,"mandamosLoc", Location1)
Subs.mandaLoc2(Location1, Starter.devModel)
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)")
' If Starter.logger Then Log("Loc changed : "&Location1.Latitude&","&Location1.Longitude&"|"&Starter.devModel&"|")
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
Sub flp_ConnectionSuspended(SuspendedCause1 As Int)
Dim Cause As String
Log("ConnectionSuspended")
Subs.bitacora("ConnectionSuspended")
If(SuspendedCause1=flp.SuspendedCause.CAUSE_NETWORK_LOST) Then
Cause="Suspended by NetworkLost"
Else If(SuspendedCause1=flp.SuspendedCause.CAUSE_SERVICE_DISCONNECTED) Then
Cause="Suspended by Disconnected"
Else
Cause="Suspended: Unknow cause"
End If
Cause = Cause&": "& Subs.fechaNormal(DateTime.Now)
LogColor(Cause, Colors.magenta)
Subs.bitacora(Cause)
flp.Disconnect
Sleep(5000)
flp.Connect
End Sub
Sub Service_Destroy
@@ -194,5 +193,4 @@ Sub Service_Destroy
Tracking = False
lock.ReleasePartialLock
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

16
test.bas Normal file
View File

@@ -0,0 +1,16 @@
B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Receiver
Version=12.5
@EndOfDesignText@
Sub Process_Globals
End Sub
'Called when an intent is received.
'Do not assume that anything else, including the starter service, has run before this method.
Private Sub Receiver_Receive (FirstTime As Boolean, StartingIntent As Intent)
End Sub