mirror of
https://github.com/KeymonSoft/Durakelo.git
synced 2026-04-17 19:36:12 +00:00
253 lines
9.8 KiB
QBasic
253 lines
9.8 KiB
QBasic
B4A=true
|
|
Group=Default Group
|
|
ModulesStructureVersion=1
|
|
Type=Service
|
|
Version=10.2
|
|
@EndOfDesignText@
|
|
'///////////////////////////////////////////////////////////////////////////////////////
|
|
'/// Agregar estas lineas al editor de manifiestos
|
|
'
|
|
' CreateResourceFromFile(Macro, FirebaseAnalytics.GooglePlayBase)
|
|
' CreateResourceFromFile(Macro, FirebaseAnalytics.Firebase)
|
|
' CreateResourceFromFile(Macro, FirebaseAnalytics.FirebaseAnalytics)
|
|
' CreateResourceFromFile(Macro, FirebaseNotifications.FirebaseNotifications)
|
|
'
|
|
'/// Agregar modulo de servicio nuevo FirebaseMessaging y copiar este modulo
|
|
'
|
|
'/// Bajar el archivo google-services.json de la consola de Firebase (https://console.firebase.google.com/)
|
|
'/// El nombre de la app en el archivo json tiene que ser el mismo que el nombre del paquete (Proyecto/Conf de Compilacion/Paquete)
|
|
'
|
|
'/// En Starter agregar esta linea
|
|
'
|
|
' Sub Service_Create
|
|
' CallSubDelayed(FirebaseMessaging, "SubscribeToTopics")
|
|
' End Sub
|
|
'
|
|
'/// En Main en Sub Process_Globals agregar esta linea
|
|
'
|
|
' Private const API_KEY As String = "AAAAv__xxxxxxxxxxxxx-xxxxxxxxxxxxxx-xxxxxxxxxxxx"
|
|
'
|
|
'/// Esta llave se consigue igualmente en la consola de Firebase, configuracion de proyecto, Cloud Messaging,
|
|
'/// es la clave de servidor.
|
|
'///
|
|
'/// Se necesitan agregar las librerías: FirebaseAnalitics, FirebaseNotifications, JSON y OkHttpUtils2
|
|
'/// ... JSON es necesario si se van a enviar mensajes, si solo se van a recibir, no es necesario.
|
|
'
|
|
'///////////////////////////////////////////////////////////////////////////////////////
|
|
|
|
Sub Process_Globals
|
|
Private fm As FirebaseMessaging
|
|
Private const API_KEY As String = "AAAAv1qt3Lk:APA91bECIR-pHn6ul53eYyoVlpPuOo85RO-0zcAgEXwE7vqw8DFSbBtCaCINiqWQAkBBZXxHtQMdpU6B-jHIqgFKVL196UgwHv0Gw6_IgmipfV_NiItjzlH9d2QNpGLp9y_JUKVjUEhP"
|
|
Dim locRequest As String
|
|
Dim phn As Phone
|
|
Dim devModel As String
|
|
Dim pe As PhoneEvents
|
|
Dim c As Cursor
|
|
Public GZip As GZipStrings
|
|
Dim Subscrito As String = ""
|
|
Dim au As String
|
|
Dim puntosRuta As Int = 380
|
|
End Sub
|
|
|
|
Sub Service_Create
|
|
fm.Initialize("fm") 'Inicializamos FirebaseMessaging
|
|
pe.Initialize("pe") 'Para obtener la bateria
|
|
End Sub
|
|
|
|
Public Sub SubscribeToTopics
|
|
' fm.SubscribeToTopic("Trckr") 'Global (you can subscribe to more topics)
|
|
fm.SubscribeToTopic("Trckr") 'Tracker global
|
|
Log("Subscrito al tracker global")
|
|
fm.SubscribeToTopic("Trckr-Durakelo") 'Global (you can subscribe to more topics)
|
|
Log("Subscrito a Trckr-Durakelo")
|
|
If Starter.usuario <> Subscrito Then
|
|
fm.SubscribeToTopic(Starter.usuario) 'Propio (you can subscribe to more topics)
|
|
fm.UnsubscribeFromTopic(Subscrito) 'Unsubscribe from topic
|
|
End If
|
|
If Starter.logger Then Log("Subscrito a "&Starter.usuario)
|
|
Subscrito = Starter.usuario
|
|
End Sub
|
|
|
|
Sub Service_Start (StartingIntent As Intent)
|
|
If StartingIntent.IsInitialized Then fm.HandleIntent(StartingIntent)
|
|
Sleep(0)
|
|
Service.StopAutomaticForeground 'remove if not using B4A v8+.
|
|
StartServiceAt(Me, DateTime.Now + 10 * DateTime.TicksPerMinute, True) 'Iniciamos servicio cada XX minutos
|
|
End Sub
|
|
|
|
Sub fm_MessageArrived (Message As RemoteMessage)
|
|
If Starter.logger Then Log("Message arrived")
|
|
If Starter.logger Then Log($"Message data: ${Message.GetData}"$)
|
|
' getPhnId
|
|
If Message.GetData.ContainsKey("t") Then
|
|
Dim tipos As List = Regex.Split(",",Message.GetData.Get("t"))
|
|
If tipos.IndexOf("pu") <> -1 Or tipos.IndexOf("au") <> -1 Then 'Si es una peticion de ubicacion
|
|
If Starter.logger Then Log("Es una peticion de ubicacion")
|
|
locRequest="Activa"
|
|
If Starter.logger Then Log("Llamamos StartFLP2Reqs")
|
|
CallSubDelayed(Tracker, "StartFLP2Reqs")
|
|
CallSubDelayed(Tracker, "StartFLP")
|
|
End If
|
|
If tipos.IndexOf("au") <> -1 Then 'Si es una actualizacion de ubicacion
|
|
au = 1
|
|
End If
|
|
If tipos.IndexOf("ping") <> -1 Then 'Si es un ping
|
|
If Starter.logger Then Log("Es un ping")
|
|
If Starter.logger Then Log("Mandamos pong")
|
|
Dim params As Map = CreateMap("topic":"Sprv-Durakelo","title":"pong", "body":Starter.usuario&" - Recibi mensaje "&Message.GetData.Get("title"), "t":"pong")
|
|
SendMessage(params)
|
|
End If
|
|
If tipos.IndexOf("bgps") <> -1 Then 'Si es una instruccion de borrar archivo gps
|
|
If Starter.logger Then Log("Es una instruccion de borrar archivo gps")
|
|
If Starter.logger Then Log("Borramos archivo gps")
|
|
borramosArchivoGPS
|
|
End If
|
|
If tipos.IndexOf("dr") <> -1 Then 'Si es una peticion de ruta gps
|
|
If Starter.logger Then Log("Es una peticion de Ruta GPS")
|
|
Dim rutaGpsCmp As String = dameRuta
|
|
Dim params As Map = CreateMap("topic":"Sprv-Durakelo","title":"ruta", "body":Starter.usuario&" - Recibi mensaje "&Message.GetData.Get("title"), "t":"ruta", "r":rutaGpsCmp)
|
|
SendMessage(params)
|
|
End If
|
|
If tipos.IndexOf("bgps2") <> -1 Then 'Si es una instruccion de borrar DB gps
|
|
If Starter.logger Then Log("Es una instruccion de borrar BD gps")
|
|
If Starter.logger Then Log("Borramos BD gps")
|
|
borraGPSHist
|
|
End If
|
|
If tipos.IndexOf("pu") = -1 And tipos.IndexOf("au") = -1 And tipos.IndexOf("ping") = -1 And tipos.IndexOf("dr") = -1 Then
|
|
If Starter.logger Then Log("No es ping ni solicitud de ubicacion o ruta, entonces no hacemos nada")
|
|
End If
|
|
End If
|
|
End Sub
|
|
|
|
Sub Service_Destroy
|
|
|
|
End Sub
|
|
|
|
Sub SendMessage(params As Map)
|
|
' Dim topic As String= params.Get("topic")
|
|
' Dim title As String= params.Get("title")
|
|
' Dim body As String= params.Get("body")
|
|
' Dim tipo As String= params.Get("t")
|
|
' If params.ContainsKey("r") Then
|
|
' If Starter.logger Then Log("Con ruta")
|
|
' Dim rutaGpsCmp As String= params.Get("r")
|
|
' Else
|
|
' If Starter.logger Then Log("Sin ruta")
|
|
' Dim rutaGpsCmp As String = ""
|
|
' End If
|
|
' Dim Job As HttpJob
|
|
' Job.Initialize("fcm", Me)
|
|
' Dim m As Map = CreateMap("to": $"/topics/${topic}"$)
|
|
' Dim data As Map = CreateMap("title":title, "body":body, "d":Starter.usuario, "t":tipo, "b":Main.batt, "mt":Main.montoActual, "r":rutaGpsCmp, "v":Main.v)
|
|
' m.Put("data", data)
|
|
' Dim jg As JSONGenerator
|
|
' jg.Initialize(m)
|
|
' Job.PostString("https://fcm.googleapis.com/fcm/send", jg.ToString)
|
|
' Job.GetRequest.SetContentType("application/json;charset=UTF-8")
|
|
' Job.GetRequest.SetHeader("Authorization", "key=" & API_KEY)
|
|
' If Starter.logger Then Log(m)
|
|
End Sub
|
|
|
|
Sub mandamosLoc(coords As String)
|
|
' If Starter.logger Then Log("Iniciamos mandamosLoc "&coords)
|
|
' If Starter.logger Then Log("locRequest="&locRequest)
|
|
' Dim t As String
|
|
' guardaInfoEnArchivo(coords)'Escribimos coordenadas y fecha a un archivo de texto
|
|
' If locRequest="Activa" Then 'Si hay solicitud de ubicacion, entonces la mandamos ...
|
|
' If au = 1 Then
|
|
' t = "au" ' es una actualizacion
|
|
' Else
|
|
' t = "u" ' es una peticion
|
|
' End If
|
|
' Dim params As Map = CreateMap("topic":"Sprv-Durakelo","title":"ubicacionRecibida", "body":coords, "t":t)
|
|
' SendMessage(params)
|
|
' locRequest="Enviada"
|
|
' CallSubDelayed(Tracker,"CreateLocationRequest")
|
|
' End If
|
|
End Sub
|
|
|
|
Sub guardaInfoEnArchivo(coords As String) 'Escribimos coordenadas y fecha a un archivo de texto
|
|
'' 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
|
|
'
|
|
' If Starter.logger Then Log("Guardamos ubicacion en db")
|
|
' Dim latlon() As String = Regex.Split(",", coords)
|
|
' Try
|
|
' Main.skmt.ExecNonQuery2("INSERT INTO RUTA_GPS(fecha, lat, lon) VALUES (?,?,?)", Array As Object (latlon(2),latlon(0),latlon(1)))
|
|
' Catch
|
|
' If Starter.logger Then Log("Error guardando ubicacion") 'Si la horaMinSeg es el mismo no lo guarda
|
|
' Log(LastException)
|
|
' End Try
|
|
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 pe_BatteryChanged (Level As Int, Scale As Int, Plugged As Boolean, Intent As Intent)
|
|
' Main.batt=Level
|
|
End Sub
|
|
|
|
Sub compress(str As String) As String
|
|
' Compression
|
|
Private su As StringUtils
|
|
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
|
|
' Decompression
|
|
Private su As StringUtils
|
|
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}"$) ' 6163 Bytes
|
|
If Starter.logger Then Log($"Decompressed String = ${uncompressed}"$)
|
|
Return uncompressed
|
|
End Sub
|
|
|
|
Sub dameRuta As String
|
|
' If Starter.logger Then Log("dameRuta")
|
|
' Dim OrigFormat As String = DateTime.DateFormat 'save orig date format
|
|
' DateTime.DateFormat="yyMMdd"
|
|
'' Dim lastUpdate As String=DateTime.Date(fecha)
|
|
' Dim hoy As String = DateTime.Date(DateTime.Now)&"000000"
|
|
' DateTime.DateFormat=OrigFormat 'return to orig date format
|
|
' If Starter.logger Then Log(hoy)
|
|
' Dim c As Cursor
|
|
' c = Main.skmt.ExecQuery("select LAT, LON from RUTA_GPS where fecha > "& hoy &" order by fecha desc limit "&puntosRuta)
|
|
' 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")
|
|
' Next
|
|
' End If
|
|
' c.Close
|
|
' Return compress(ruta2)
|
|
End Sub
|
|
|
|
Sub borraGPSHist
|
|
' c=Main.skmt.ExecQuery("select count(*) as cuantos FROM RUTA_GPS")
|
|
' c.Position=0
|
|
' If Starter.logger Then Log(c.GetInt("cuantos"))
|
|
' Main.skmt.ExecNonQuery("delete from RUTA_GPS")
|
|
' c=Main.skmt.ExecQuery("select count(*) as cuantos FROM RUTA_GPS")
|
|
' c.Position=0
|
|
' Log(c.GetInt("cuantos"))
|
|
' Log("Borramos RUTA_GPS")
|
|
' c.Close
|
|
End Sub |