diff --git a/B4A/B4XMainPage.bas b/B4A/B4XMainPage.bas index 0981b11..b2dc630 100644 --- a/B4A/B4XMainPage.bas +++ b/B4A/B4XMainPage.bas @@ -22,13 +22,6 @@ Sub Class_Globals Private xui As XUI Public login As B4XMainPage Dim s As C_Subs - - Dim reqManager As DBRequestManager - Dim ruta As String - - Dim batterystatus(11) As Int - Private bu As BatteryUtilities - Private tb_monitorActivo As ToggleButton Private b_monitorActivo As Button Private p_bMonitor As Panel Private l_version As Label @@ -37,6 +30,24 @@ Sub Class_Globals Dim cb_internet As CheckBox Dim cb_dbreqserver As CheckBox Dim cb_db As CheckBox + Private b_intervalo As Button + Private b_server As Button + Private et_server As EditText + Private lv_server As ListView + Private i_engrane As ImageView + Private p_engrane As Panel + Dim b_ping As Button + Private cd1 As ColorDrawable + Dim l_ultimoPing As Label + Private p_intervalo As Panel + Private et_intervalo As EditText + Private p_timeout As Panel + Private et_timeout As EditText + Private l_timeout As Label + Private b_timeout As Button + Private Label1 As Label + Private b_notifAccess As Button + Dim logger As Boolean = False End Sub Public Sub Initialize @@ -47,76 +58,150 @@ End Sub Private Sub B4XPage_Created (Root1 As B4XView) Root = Root1 Root.LoadLayout("login") - B4XPages.SetTitle(Me, "Tester") + B4XPages.SetTitle(Me, "Monitor Keymon") B4XPages.AddPage("Login", login) s.Initialize l_version.Text = Application.VersionName -' ruta = Starter.ruta -' If File.Exists(ruta, "kmt.db") = False Then -' File.Copy(File.DirAssets, "kmt.db", ruta, "kmt.db") -' Log(File.DirAssets) -' LogColor("copiamos kmt.db de "&File.DirAssets & " a " & ruta,Colors.Green) -' End If - If Starter.logger Then Log(ruta) -' skmt.Initialize(ruta,"kmt.db", True) -' Subs.guardaAppInfo(skmt) + lv_server.AddSingleLine("http://keymon.lat:1782") + lv_server.AddSingleLine("http://10.0.0.205:1782") + et_server.Text = Starter.DBReqServer + #if not(DEBUG) + logger = False + #end if End Sub Sub B4XPage_Appear - reqManager.Initialize(Me, Starter.server) - bu.Initialize - batterystatus = bu.BatteryInformation - s.centraPanel(p_bMonitor, Root.Width) +' reqManager.Initialize(Me, Starter.DBReqServer) + cd1.Initialize(Colors.RGB(16, 141, 0), 10dip) + b_ping.Background = cd1 +' bu.Initialize +' batterystatus = bu.BatteryInformation + b_monitorActivo.Left = (Root.Width / 2) - (b_monitorActivo.Width / 2) + b_ping.Left = (Root.Width / 2) - (b_ping.Width / 2) s.centraPanel(p_estatus, Root.Width) s.centraEtiqueta(l_status, Root.Width) -End Sub - -Sub JobDone(Job As HttpJob) - If Starter.logger Then Log(Job.Success) - If Job.Success = False Then -' ToastMessageShow("Error: " & Job.ErrorMessage, True) + s.centraEtiqueta(l_ultimoPing, Root.Width) + s.centraPanel(p_intervalo, Root.Width) + s.centraEtiqueta(Label1, Root.Width) + If Not(CheckNotificationAccess) Then + Private cd1 As ColorDrawable + cd1.Initialize(Colors.red, 10dip) + b_notifAccess.Background = cd1 + b_notifAccess.TextColor = Colors.White + b_notifAccess.Text = "Activar Permisos" Else - If Starter.logger Then LogColor("JobDone: '" & reqManager.HandleJob(Job).tag & "' - Registros: " & reqManager.HandleJob(Job).Rows.Size, Colors.Green) 'Mod por CHV - 211027 - - If Job.JobName = "DBRequest" Then - Dim result As DBResult = reqManager.HandleJob(Job) - If result.Tag = "agencia" Then 'query tag - For Each records() As Object In result.Rows - Dim ID_ALMACEN As String = records(result.Columns.Get("ID_ALMACEN")) - Next - End If - End If - Job.Release + Private cd1 As ColorDrawable + cd1.Initialize(Colors.RGB(109, 221, 101), 10dip) + b_notifAccess.Background = cd1 + b_notifAccess.TextColor = Colors.White + b_notifAccess.Text = "Permisos Activos" End If + CallSubDelayed(Monitor, "Timer1_Tick") End Sub Private Sub B4XPage_CloseRequest As ResumableSub If Starter.logger Then Log("closreq") Sleep(0) - Return True + If p_engrane.Visible Then + p_engrane.Visible = False + End If + Return False 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 Private Sub tb_monitorActivo_CheckedChange(Checked As Boolean) End Sub Private Sub b_monitorActivo_Click - Private cd1 As ColorDrawable + If logger Then Log(Starter.DBReqServer) If Starter.monitorActivo Then cd1.Initialize(Colors.red, 10dip) b_monitorActivo.Background = cd1 b_monitorActivo.Text = "Monitor Apagado" l_status.Text = "Monitor Apagado" Starter.monitorActivo = False - Starter.notiHigh("Con internet", $"Monitor apagado!!"$, Starter.nid, Main) + s.notiHigh("Con internet", $"Monitor apagado!!"$, Monitor.nid, Main) Else cd1.Initialize(Colors.RGB(16, 141, 0), 10dip) b_monitorActivo.Background = cd1 b_monitorActivo.Text = "Monitor Activo" l_status.Text = "Monitor Activo" - Starter.Timer1_Tick + CallSubDelayed(Monitor, "Timer1_Tick") Starter.monitorActivo = False Starter.monitorActivo = True End If -End Sub \ No newline at end of file +End Sub + +Private Sub lv_server_ItemClick (Position As Int, Value As Object) + If logger Then Log(Value) + et_server.Text = Value + Starter.DBReqServer = Value + Starter.skmt.ExecNonQuery($"delete from cat_variables where nombre = 'servidor'"$) + Starter.skmt.ExecNonQuery($"insert into cat_variables (nombre, valor) values ("servidor", '${Value}')"$) + CallSubDelayed(Monitor, "reinicializaReqManager") + ToastMessageShow($"Servidor modificado"$, False) +End Sub + +Private Sub b_server_Click + Starter.DBReqServer = et_server.text + Starter.skmt.ExecNonQuery($"delete from cat_variables where nombre = 'servidor'"$) + Starter.skmt.ExecNonQuery($"insert into cat_variables (nombre, valor) values ("servidor", '${et_server.text}')"$) + CallSubDelayed(Monitor, "reinicializaReqManager") + ToastMessageShow($"Servidor modificado"$, False) + p_engrane.Visible = False + CallSubDelayed(Monitor, "Timer1_Tick") +End Sub + +Private Sub b_intervalo_Click + Monitor.Interval = et_intervalo.text + Starter.skmt.ExecNonQuery($"delete from cat_variables where nombre = 'intervalo'"$) + Starter.skmt.ExecNonQuery($"insert into cat_variables (nombre, valor) values ("intervalo", '${et_intervalo.text}')"$) + ToastMessageShow($"Intervalo modificado"$, False) + CallSubDelayed(Monitor, "Timer1_Tick") + p_engrane.Visible = False +End Sub + +Private Sub i_engrane_Click + et_intervalo.Text = s.traeIntervaloDeBD + et_timeout.Text = s.traeTimeoutDeBD + p_engrane.Width = Root.Width + p_engrane.Height = Root.Height + s.panelVisible(p_engrane, 0, 0) +End Sub + +Private Sub p_engrane_Click + +End Sub + +Private Sub b_ping_Click + cd1.Initialize(Colors.RGB(5, 104, 0), 10dip) + b_ping.Background = cd1 + b_ping.Text = "Buscando ..." + CallSubDelayed(Monitor, "Timer1_Tick") +End Sub + +Private Sub b_timeout_Click + Monitor.timeout = et_timeout.text + Starter.skmt.ExecNonQuery($"delete from cat_variables where nombre = 'timeout'"$) + Starter.skmt.ExecNonQuery($"insert into cat_variables (nombre, valor) values ("timeout", '${et_timeout.text}')"$) + ToastMessageShow($"Intervalo modificado"$, False) + CallSubDelayed(Monitor, "Timer1_Tick") + p_engrane.Visible = False +End Sub + +'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage. +Sub b_notifAccess_Click + Dim In As Intent + In.Initialize("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS", "") + StartActivity(In) +End Sub diff --git a/B4A/C_Subs.bas b/B4A/C_Subs.bas index 2ca1fe1..f2da875 100644 --- a/B4A/C_Subs.bas +++ b/B4A/C_Subs.bas @@ -7,15 +7,15 @@ Version=12.2 Sub Class_Globals 'These global variables will be declared once when the application starts. 'These variables can be accessed from all modules. - Public GZip As GZipStrings 'Usa la libreria CompressStrings - Private su As StringUtils 'Usa la libreria StringUtils +' Public GZip As GZipStrings 'Usa la libreria CompressStrings +' Private su As StringUtils 'Usa la libreria StringUtils Dim phn As Phone Dim devModel As String - Dim kmt, errorLog As SQL 'Requiere la libreria "SQL" + Dim kmt, errorLog As SQL 'Requiere la libreria "SQL" 'ignore ' Dim wifi As MLwifi Dim ssid As String 'ignore - Dim rutaMaxPoints As Int = 3000 - Dim rutaHrsAtras As Int = 48 +' Dim rutaMaxPoints As Int = 3000 +' Dim rutaHrsAtras As Int = 48 ' Dim rutaInicioHoy As String = "" Private subsLogs As Boolean = False End Sub @@ -46,29 +46,6 @@ Sub getPhnId As String 'ignore Return devModel End Sub -'Comprime y regresa un texto (str) en base64 -Sub compress(str As String) As String 'ignore - 'Requiere la libreria "CompressStrings" - Dim compressed() As Byte = GZip.compress(str) -' Log($"UncompressedBytesLength: ${str.Length}"$) -' Log($"CompressedBytesLength: ${compressed.Length}"$) - Dim base64 As String = su.EncodeBase64(compressed) - Log($"Comprimido: ${base64.Length}"$) -' Log($"CompressedBytes converted to base64: ${base64}"$) - Return base64 -End Sub - -'Descomprime y regresa un texto en base64 -Sub decompress(base64 As String) As String 'ignore - Dim decompressedbytes() As Byte = su.DecodeBase64(base64) -' Log($"decompressedbytesLength: ${decompressedbytes.Length}"$) - Dim bc As ByteConverter - Dim uncompressed As String = bc.StringFromBytes(decompressedbytes,"UTF8") - Log($"Descomprimido: ${uncompressed.Length}"$) -' Log($"Decompressed String = ${uncompressed}"$) - Return uncompressed -End Sub - 'Convierte una fecha al formato yyMMddHHmmss Sub fechaKMT(fecha As String) As String 'ignore ' Log(fecha) @@ -81,32 +58,32 @@ Sub fechaKMT(fecha As String) As String 'ignore End Sub 'Genera una notificacion con importancia alta -Sub notiHigh(title As String, body As String, activity As Object) 'ignore - Private notif As Notification - notif.Initialize2(notif.IMPORTANCE_HIGH) - notif.Icon = "icon" - notif.Vibrate = False - notif.Sound = False - notif.AutoCancel = True - Log("notiHigh: "&title) - notif.SetInfo(title, body, activity) -' Log("notiHigh SetInfo") - notif.Notify(777) -End Sub +'Sub notiHigh(title As String, body As String, activity As Object) 'ignore +' Private notif As Notification +' notif.Initialize2(notif.IMPORTANCE_HIGH) +' notif.Icon = "icon" +' notif.Vibrate = False +' notif.Sound = False +' notif.AutoCancel = True +' Log("notiHigh: "&title) +' notif.SetInfo(title, body, activity) +'' Log("notiHigh SetInfo") +' notif.Notify(777) +'End Sub 'Regresa el objeto de una notificacion con importancia baja -Sub notiLowReturn(title As String, Body As String, id As Int) As Notification 'ignore - Private notification As Notification - notification.Initialize2(notification.IMPORTANCE_LOW) - Log("notiLowReturn: "&title) - notification.Icon = "icon" - notification.Sound = False - notification.Vibrate = False - notification.SetInfo(title, Body, Main) - notification.Notify(id) -' Log("notiLowReturn SetInfo") - Return notification -End Sub +'Sub notiLowReturn(title As String, Body As String, id As Int) As Notification 'ignore +' Private notification As Notification +' notification.Initialize2(notification.IMPORTANCE_LOW) +' Log("notiLowReturn: "&title) +' notification.Icon = "icon" +' notification.Sound = False +' notification.Vibrate = False +' notification.SetInfo(title, Body, Main) +' notification.Notify(id) +'' Log("notiLowReturn SetInfo") +' Return notification +'End Sub 'Escribimos las coordenadas y fecha a un archivo de texto Sub guardaInfoEnArchivo(coords As String) 'ignore @@ -151,39 +128,6 @@ Sub deleteErrorLog_DB 'ignore ToastMessageShow("BD Errores Borrada", False) End Sub -'Borramos el archio "gps.txt" -Sub borramosArchivoGPS 'ignore - 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 - -'Convierte un texto en formato JSON a un objeto "Map" -Sub JSON2Map(theJson As String) As Map 'ignore - 'Requiere la libreria "JSON" - Try - Private json As JSONParser - json.Initialize(theJson) - Return json.NextObject - Catch - Log(LastException) - log2DB("JSON2Map: "&LastException) - Private m As Map = CreateMap("title":"Error generating JSON", "t":"Error", "Message":LastException, "text" : LastException) - Return m - End Try -End Sub - -'Convierte un mapa a formato JSON -Sub map2JSON(m As Map) As String 'ignore - 'Requiere la libreria "JSON" - 'Convierte un objecto "Map" a JSON - Dim jg As JSONGenerator - jg.Initialize(m) - Dim t As String = jg.ToString - Return t -End Sub 'Mandamos "coords" en un mensaje a "Sprvsr" 'Sub mandamosLoc(coords As String) 'ignore @@ -273,36 +217,6 @@ End Sub ' If monitorStatus Then LogColor(" +++ +++ Servicios Activos", Colors.Green) 'End Sub -'Regresa la tabla "errores" en una lista de mapas convertida a JSON -Sub dameErroresJSON(SQL As SQL, maxErrores As Int, comprimido As Boolean) As String 'ignore - Log("dameErroresJSON") - Private j As JSONGenerator - Private lim As String - Private cur As ResultSet - Private l As List - Private i As Int = 0 - l.Initialize - Dim m, m2 As Map - m2.Initialize - If maxErrores = 0 Then lim = "" Else lim = "limit "&maxErrores - cur = SQL.ExecQuery("select * from errores order by fecha desc "&lim) - Do While cur.NextRow - m.Initialize - m.Put("fecha", cur.GetString("fecha")) - m.Put("error", cur.GetString("error")) - m2.Put(i,m) - i = i + 1 - Loop - cur.Close - j.Initialize(m2) - Log(j.ToString) - If comprimido Then - Return compress(j.ToString) - Else - Return j.ToString - End If -End Sub - 'Convierte una fecha en formato YYMMDDHHMMSS a Ticks Sub fechaKMT2Ticks(fKMT As String) As Long 'ignore Try @@ -407,31 +321,6 @@ Sub buscaDBUsuario As String 'ignore Return usuario End Sub -''Inserta un producto en la tabla "PEDIDO" -'Sub guardaProductoX(cedis As String, costoTot As String, costoU As String, cant As String, nombre As String, prodId As String, clienteId As String, fecha As String, usuario As String, tipoV As String, precio2 As String, query As String) 'ignore -'' LogColor("guardaProducto", Colors.Magenta) -'' Log($"Guardamos producto ${prodId}"$) -'' B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO PEDIDO (PE_CEDIS, PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_CLIENTE, PE_FECHA, PE_USUARIO, PE_TIPO, PE_PRECIO2, PE_RUTA) VALUES(?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (cedis, costoTot, costoU, cant, nombre, prodId, clienteId, fecha, usuario, tipoV, precio2, Starter.rutaV)) -'' B4XPages.MainPage.skmt.ExecNonQuery2("update " & query & " set cat_gp_almacen = cat_gp_almacen - ? where cat_gp_id = ? ", Array As Object(cant, prodId)) -'' ToastMessageShow("guardaProd", False) -'End Sub - -'Sub guardaProductoSin(cedis As String, costoTot As String, costoU As String, cant As String, nombre As String, prodId As String, clienteId As String, fecha As String, usuario As String, rutaV As String, precioSin As String, tipoV As String, precio2 As String, query As String) 'ignore -'' LogColor("guardaProductoSin", Colors.Magenta) -'' B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO PEDIDO (PE_CEDIS, PE_COSTO_TOT, PE_COSTOU, PE_CANT, PE_PRONOMBRE, PE_PROID, PE_CLIENTE, PE_FECHA, PE_USUARIO, PE_RUTA, PE_COSTO_SIN, PE_TIPO, PE_PRECIO2) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (cedis, costoTot,costoU, cant, nombre, prodId, clienteId, fecha, usuario, rutaV, precioSin, tipoV, precio2)) -'' B4XPages.MainPage.skmt.ExecNonQuery2("update " & query & " set cat_gp_almacen = cat_gp_almacen - ? where cat_gp_id = ? ", Array As Object(cant, prodId)) -'' DateTime.DateFormat = "MM/dd/yyyy" -'' Private sDate As String =DateTime.Date(DateTime.Now) -'' Private sTime As String =DateTime.Time(DateTime.Now) -'' Private c As Cursor = B4XPages.MainPage.skmt.ExecQuery("select sum(pe_costo_tot) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE, SUM(PE_COSTO_SIN) AS TOTAL_CLIE_SIN FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)") -'' c.Position=0 -'' B4XPages.MainPage.skmt.ExecNonQuery("delete from pedido_cliente where PC_CLIENTE In (select cuenta from cuentaa)") -'' B4XPages.MainPage.skmt.ExecNonQuery2("insert into pedido_cliente(PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT,PC_ALMACEN,PC_RUTA,PC_COSTO_SIN) VALUES (?,?,?,?,?,?,?,?,?,?)", Array As Object(clienteId, sDate & sTime, usuario, c.GetString("CANT_CLIE"),c.GetString("TOTAL_CLIE"), B4XPages.MainPage.lon_gps, B4XPages.MainPage.lat_gps, cedis, rutaV, c.GetString("TOTAL_CLIE_SIN"))) -'' B4XPages.MainPage.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 2 where CAT_CL_CODIGO In (select cuenta from cuentaa)") -'' c.Close -' ToastMessageShow("guardaProdSin", False) -'End Sub - Sub traeFecha As String 'ignore DateTime.DateFormat = "MM/dd/yyyy" Private sDate As String =DateTime.Date(DateTime.Now) @@ -440,7 +329,7 @@ Sub traeFecha As String 'ignore End Sub 'Guarda el nombre y version de la app en CAT_VARIABLES. -Sub guardaAppInfo(skmt As SQL) +Sub guardaAppInfo(skmt As SQL) 'ignore skmt.ExecNonQuery("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'EMPRESA' or CAT_VA_DESCRIPCION = 'APP_NAME' or CAT_VA_DESCRIPCION = 'APP_VERSION'") skmt.ExecNonQuery($"insert into CAT_VARIABLES (CAT_VA_DESCRIPCION, CAT_VA_VALOR) values ('APP_NAME', '${Application.LabelName}')"$) skmt.ExecNonQuery($"insert into CAT_VARIABLES (CAT_VA_DESCRIPCION, CAT_VA_VALOR) values ('APP_VERSION', '${Application.VersionName}')"$) @@ -454,4 +343,106 @@ Sub logJobDoneResultados(resultado As DBResult) 'ignore LogColor(k & " = " & records(resultado.Columns.Get(k)), Colors.RGB(215,37,0)) Next Next +End Sub + +'Regresa la base de datos espscificada ya inicializada. +Sub inicializaBD(ruta As String, BDName As String) As SQL + Dim skmt As SQL + If File.Exists(ruta, BDName) = False Then + File.Copy(File.DirAssets, BDName, ruta, BDName) + LogColor($"Copiamos ${BDName} de ${File.DirAssets} a ${ruta}"$,Colors.Green) + End If + skmt.Initialize(ruta, BDName, True) + Return skmt +End Sub + +'Agrega una columna a la tabla especificada. +'Hay que indicar el "tipo" de la columna (TEXT, INTEGER, ETC) +'Ej. agregaColumna("TABLA", "COLUMNA", "TIPO") +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 = Starter.skmt.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 + Starter.skmt.ExecNonQuery($"ALTER TABLE ${tabla} ADD COLUMN ${columna} ${tipo}"$) + Log($"Columna "${columna} ${tipo}", agregada a "${tabla}"."$) + End If + Catch 'Si no funciona "pragma_table_info" lo hacemos con try/catch + Try + Starter.skmt.ExecNonQuery($"ALTER TABLE ${tabla} ADD COLUMN ${columna} ${tipo}"$) + Log($"Columna "${columna} ${tipo}", agregada a "${tabla}".."$) + Catch + Log(LastException) + End Try + End Try +End Sub + +'Regresa el el DBReqServer desde la base de datos o "N/A" si no existe. +Sub traeDBReqServerDeBD As String 'ignore + Dim srvr As String = "N/A" + Dim rs As ResultSet = Starter.skmt.ExecQuery("select valor from cat_variables where nombre = 'servidor'") + If rs.RowCount > 0 Then + rs.NextRow + srvr = rs.GetString("valor") + End If + Return srvr +End Sub + +'Regresa el el intervalo desde la base de datos o "30" si no existe. +Sub traeIntervaloDeBD As String 'ignore + Dim intrvl As String = "30" + Dim rs As ResultSet = Starter.skmt.ExecQuery("select valor from cat_variables where nombre = 'intervalo'") + If rs.RowCount > 0 Then + rs.NextRow + intrvl = rs.GetString("valor") + End If + Return intrvl +End Sub + +'Regresa el timeout desde la base de datos o "1250" si no existe. +Sub traeTimeoutDeBD As String 'ignore + Dim tmout As String = "1250" + Dim rs As ResultSet = Starter.skmt.ExecQuery("select valor from cat_variables where nombre = 'timeout'") + If rs.RowCount > 0 Then + rs.NextRow + tmout = rs.GetString("valor") + End If + Return tmout +End Sub + +Sub CreateNotification (Body As String) As Notification + Dim notification As Notification + notification.Initialize2(notification.IMPORTANCE_LOW) + notification.Icon = "icon" + notification.SetInfo("Tester", Body, Main) + Return notification +End Sub + +'Genera una notificacion con importancia alta +Sub notiHigh(title As String, body As String, id As String, activity As Object) 'ignore + activity = Main + Private notif As Notification + notif.Initialize2(notif.IMPORTANCE_HIGH) + notif.Icon = "icon" + notif.Vibrate = False + notif.Sound = False + notif.AutoCancel = True +' If logger Then Log("notiHigh: "&title) + notif.SetInfo(title, body, activity) +' Log("notiHigh SetInfo") + notif.Notify(id) +End Sub + +'Regresa el objeto de una notificacion con importancia baja +Sub notiLowReturn(title As String, Body As String, id As Int) As Notification 'ignore + Private notification As Notification + notification.Initialize2(notification.IMPORTANCE_LOW) +' Log("notiLowReturn: "&title) + notification.Icon = "icon" + notification.Sound = False + notification.Vibrate = False + notification.SetInfo(title, Body, Main) + notification.Notify(id) +' Log("notiLowReturn SetInfo") + Return notification End Sub \ No newline at end of file diff --git a/B4A/DBRequestManager.bas b/B4A/DBRequestManager.bas index 74d6542..dec4d83 100644 --- a/B4A/DBRequestManager.bas +++ b/B4A/DBRequestManager.bas @@ -18,6 +18,7 @@ Sub Class_Globals Private VERSION As Float = 0.9 Private tempArray(1) As Object Dim jobTagAnterior As String = "" 'Mod por CHV - 211027 + Dim logger As Boolean = False End Sub 'Target - The module that handles JobDone (usually Me). @@ -25,6 +26,9 @@ End Sub Public Sub Initialize (Target As Object, ConnectorLink As String) mTarget = Target link = ConnectorLink + #if not(DEBUG) + logger = False + #end if End Sub 'Sends a query request. @@ -188,7 +192,7 @@ End Sub 'Handles the Job result and returns a DBResult. Public Sub HandleJob(Job As HttpJob) As DBResult - Dim start As Long = DateTime.Now +' Dim start As Long = DateTime.Now Dim In As InputStream = Job.GetInputStream Dim cs As CompressedStreams In = cs.WrapInputStream(In, "gzip") @@ -255,13 +259,13 @@ End Sub 'Prints the table to the logs. Public Sub PrintTable(Table As DBResult) - Log("Tag: " & Table.Tag & ", Columns: " & Table.Columns.Size & ", Rows: " & Table.Rows.Size) + If logger Then Log("Tag: " & Table.Tag & ", Columns: " & Table.Columns.Size & ", Rows: " & Table.Rows.Size) Dim sb As StringBuilder sb.Initialize For Each col In Table.Columns.Keys sb.Append(col).Append(TAB) Next - Log(sb.ToString) + If logger Then Log(sb.ToString) For Each row() As Object In Table.Rows Dim sb As StringBuilder sb.Initialize diff --git a/B4A/Files/engrane.png b/B4A/Files/engrane.png new file mode 100644 index 0000000..8b45d09 Binary files /dev/null and b/B4A/Files/engrane.png differ diff --git a/B4A/Files/kmt.db b/B4A/Files/kmt.db new file mode 100644 index 0000000..882b5b9 Binary files /dev/null and b/B4A/Files/kmt.db differ diff --git a/B4A/Files/login.bal b/B4A/Files/login.bal index 36f0ad9..b27e55a 100644 Binary files a/B4A/Files/login.bal and b/B4A/Files/login.bal differ diff --git a/B4A/NotificationService.bas b/B4A/NotificationService.bas new file mode 100644 index 0000000..914cfeb --- /dev/null +++ b/B4A/NotificationService.bas @@ -0,0 +1,53 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=Service +Version=11 +@EndOfDesignText@ +#Region Service Attributes + #StartAtBoot: False +#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 rp As ReplyAuto +' Dim activo As Boolean = True + Dim ultimaNoti As String + Dim logger As Boolean = False +End Sub + +Sub Service_Create + rp.Initialize("MonitorKeymon") + #if not(DEBUG) + logger = False + #end if + If logger Then Log("**************** Iniciamos Monitor Keymon ***********************") +End Sub + +Sub Service_Start (StartingIntent As Intent) + If rp.HandleIntent(StartingIntent) Then Return + DateTime.DateFormat = "mm" + ultimaNoti = DateTime.Date(DateTime.now) + If logger Then LogColor($"Ultima noti en el minuto ${ultimaNoti}"$, Colors.green) +End Sub + +Sub Service_Destroy + +End Sub + +Sub MonitorKeymon_NotificationPosted (SBN As StatusBarNotification) + If ultimaNoti = "" Then ultimaNoti = 0 + DateTime.DateFormat = "mm" + Private estaNoti As String = DateTime.Date(DateTime.now) + If estaNoti > 60 Then estaNoti = estaNoti - 60 + If logger Then LogColor("Diferencia de tiempo entre notis = " & (estaNoti - ultimaNoti), Colors.blue) + If logger Then LogColor($"Esta noti en el minuto ${DateTime.Date(DateTime.now)}, ultima noti = ${ultimaNoti}"$, Colors.green) + If logger Then Log(SBN.PackageName) + If ultimaNoti < estaNoti Then + If logger Then LogColor($"******** TIEMPO *******"$, Colors.red) + ultimaNoti = estaNoti + If IsPaused(Monitor) Then StartService(Monitor) + End If + If logger Then LogColor("Monitor inicializado:" & Monitor.Timer1.IsInitialized, Colors.Magenta) +End Sub diff --git a/B4A/Starter.bas b/B4A/Starter.bas index 516d22b..325537d 100644 --- a/B4A/Starter.bas +++ b/B4A/Starter.bas @@ -5,7 +5,7 @@ Type=Service Version=9.85 @EndOfDesignText@ #Region Service Attributes - #StartAtBoot: False + #StartAtBoot: true #ExcludeFromLibrary: True #End Region @@ -13,25 +13,25 @@ Sub Process_Globals 'These global variables will be declared once when the application starts. 'These variables can be accessed from all modules. Public rp As RuntimePermissions - Dim reqManager As DBRequestManager - Dim server As String = "http://keymon.lat:1782" - Dim Timer1 As Timer - Dim Interval As Int = 5 - Public rp As RuntimePermissions +' Dim reqManager As DBRequestManager + Dim DBReqServer As String = "http://keymon.lat:1782" + Dim skmt As SQL +' Dim Timer1 As Timer +' Dim Interval As Int = 30 Dim s As C_Subs - Dim nid As Int = 51042 +' Dim nid As Int = 51042 Dim monitorActivo As Boolean = True - Dim InternetOk As Boolean = True - Dim DBReqServerOk As Boolean = True - Dim DBOk As Boolean = True +' Dim InternetOk As Boolean = True +' Dim DBReqServerOk As Boolean = True +' Dim DBOk As Boolean = True Dim logger As Boolean = False 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. - Timer1.Initialize("Timer1", Interval * 1000) - Timer1.Enabled = True +' Timer1.Initialize("Timer1", Interval * 1000) +' Timer1.Enabled = True #if not(DEBUG) logger = False #end if @@ -39,53 +39,56 @@ End Sub Sub Service_Start (StartingIntent As Intent) Service.StopAutomaticForeground 'Starter service can start in the foreground state in some edge cases. - Service.StartForeground(nid, CreateNotification("...")) - reqManager.Initialize(Me, server) s.Initialize - Timer1_Tick -End Sub - -Sub CreateNotification (Body As String) As Notification - Dim notification As Notification - notification.Initialize2(notification.IMPORTANCE_LOW) - notification.Icon = "icon" - notification.SetInfo("Tester", Body, Main) - Return notification -End Sub - -'Genera una notificacion con importancia alta -Sub notiHigh(title As String, body As String, id As String, activity As Object) 'ignore - activity = Main - Private notif As Notification - notif.Initialize2(notif.IMPORTANCE_HIGH) - notif.Icon = "icon" - notif.Vibrate = False - notif.Sound = False - notif.AutoCancel = True - if logger then Log("notiHigh: "&title) - notif.SetInfo(title, body, activity) -' Log("notiHigh SetInfo") - notif.Notify(id) -End Sub - -'Regresa el objeto de una notificacion con importancia baja -Sub notiLowReturn(title As String, Body As String, id As Int) As Notification 'ignore - Private notification As Notification - notification.Initialize2(notification.IMPORTANCE_LOW) -' Log("notiLowReturn: "&title) - notification.Icon = "icon" - notification.Sound = False - notification.Vibrate = False - notification.SetInfo(title, Body, Main) - notification.Notify(id) -' Log("notiLowReturn SetInfo") - Return notification -End Sub - -Sub Timer1_Tick -' Log("Next run " & DateTime.Time(DateTime.Now + Interval * 1000)) - If monitorActivo Then probamosConexion + skmt = s.inicializaBD(File.DirInternal, "kmt.db") + skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS cat_variables(nombre TEXT, valor text)") + If s.traeDBReqServerDeBD <> "N/A" Then DBReqServer = s.traeDBReqServerDeBD +' reqManager.Initialize(Me, DBReqServer) + StartService(Monitor) End Sub +' +'Sub CreateNotification (Body As String) As Notification +' Dim notification As Notification +' notification.Initialize2(notification.IMPORTANCE_LOW) +' notification.Icon = "icon" +' notification.SetInfo("Tester", Body, Main) +' Return notification +'End Sub +' +''Genera una notificacion con importancia alta +'Sub notiHigh(title As String, body As String, id As String, activity As Object) 'ignore +' activity = Main +' Private notif As Notification +' notif.Initialize2(notif.IMPORTANCE_HIGH) +' notif.Icon = "icon" +' notif.Vibrate = False +' notif.Sound = False +' notif.AutoCancel = True +' If logger Then Log("notiHigh: "&title) +' notif.SetInfo(title, body, activity) +'' Log("notiHigh SetInfo") +' notif.Notify(id) +'End Sub +' +''Regresa el objeto de una notificacion con importancia baja +'Sub notiLowReturn(title As String, Body As String, id As Int) As Notification 'ignore +' Private notification As Notification +' notification.Initialize2(notification.IMPORTANCE_LOW) +'' Log("notiLowReturn: "&title) +' notification.Icon = "icon" +' notification.Sound = False +' notification.Vibrate = False +' notification.SetInfo(title, Body, Main) +' notification.Notify(id) +'' Log("notiLowReturn SetInfo") +' Return notification +'End Sub +' +'Sub Timer1_Tick +'' DateTime.DateFormat = "dd/MM HH:mm:ss" +'' If B4XPages.IsInitialized Then B4XPages.MainPage.l_ultimoPing.Text = $"Último ping: ${DateTime.Date(DateTime.now)}"$ +'' If monitorActivo Then probamosConexion +'End Sub Sub Service_TaskRemoved 'This event will be raised when the user removes the app from the recent apps list. @@ -94,109 +97,114 @@ End Sub Sub Service_Destroy End Sub - -Sub probamosConexion -' Log("probamos probamosConexion") - If B4XPages.IsInitialized Then - B4XPages.MainPage.cb_internet.Checked = False - B4XPages.MainPage.cb_dbreqserver.Checked = False - B4XPages.MainPage.cb_db.Checked = False - End If - If IsConnectedToInternet Then - InternetOk = True - If B4XPages.IsInitialized Then B4XPages.MainPage.cb_internet.Checked = True - Dim cmd As DBCommand - notiLowReturn("Con internet", "Hay conexion a internet", nid) - If B4XPages.IsInitialized Then B4XPages.MainPage.l_status.Text = "Hay conexion a internet!!" - Dim cmd As DBCommand - cmd.Initialize - cmd.Name = "select_conexion" - reqManager.ExecuteQuery(cmd, 0, "select_conexion", 750) - 'Reiniciamos el timer para cuando llamamos el Sub desde "seleccion" - Timer1.Enabled = False - Timer1.Interval = Interval * 1000 - Timer1.Enabled = True - Else - if logger then Log("Sin conexión a internet!!!") - notiLowReturn("Sin internet", "NO hay conexion a internet", nid) - If B4XPages.IsInitialized Then B4XPages.MainPage.l_status.Text = "NO hay conexion a internet!!" - End If - -End Sub - -Sub reinicializaReqManager - reqManager.Initialize(Me, server) -' B4XPages.MainPage.reqManager.Initialize(Me, server) -' If logger Then Log(server) -End Sub - - -'[b4xcollections=Null, B4XPages=Null, defaultscheme=https -'[b4xcollections=null, b4xpages=null, defaultscheme=https -', errormessage=, HttpUtils2Service=Null, invalidurl=https://invalid-url/ -', errormessage=, httputils2service=null, invalidurl=https://invalid-url/ -', jobname=DBRequest, Main=Null, out=(BufferedOutputStream) java.io.BufferedOutputStream@3406019 -', jobname=DBRequest, main=null, out=(BufferedOutputStream) java.io.BufferedOutputStream@3672b93 -', password=, req=anywheresoftware.b4h.okhttp.OkHttpClientWrapper$OkHttpRequest@c06b8de, response=anywheresoftware.b4h.okhttp.OkHttpClientWrapper$OkHttpResponse@4e48abf -', password=, req=anywheresoftware.b4h.okhttp.OkHttpClientWrapper$OkHttpRequest@8e687d0, response=anywheresoftware.b4h.okhttp.OkHttpClientWrapper$OkHttpResponse@26963c9 -', starter=Null, success=True, tag=select_conexion>XXX -', starter=null, success=true, tag=select_conexionXXX -', target=class md.keymon.com.mx.starter, taskid=8, username= -', target=class md.keymon.com.mx.starter, taskid=2, username= - - - - -Sub JobDone(Job As HttpJob) -' Log("JOBDONE -- " & Job.Success) -' Log(Job) - If Job.Success = False Then - If Job.JobName = "DBRequest" Then DBReqServerOk = False - notiHigh("Con internet", $"El servidor NO esta respondiendo!!"$, nid, Main) - If Job.ErrorMessage.Contains("failed to connect") Or Job.ErrorMessage.Contains("Failed to connect") Then - ToastMessageShow("¡Hubo un error contactando al servidor, por favor revise su conexión!", True) - End If - Else - If Job.JobName = "DBRequest" Then DBReqServerOk = True - if logger then LogColor("JobDone: '" & reqManager.HandleJob(Job).tag & "' - Registros: " & reqManager.HandleJob(Job).Rows.Size, Colors.Green) 'Mod por CHV - 211027 - If Job.JobName = "DBRequest" Then - Dim resultado As DBResult = reqManager.HandleJob(Job) - If resultado.Tag = "select_conexion" Then - For Each records() As Object In resultado.Rows - Private valor As String = records(resultado.Columns.Get("VALOR")) - If valor = "OK" Then - DBOk = True - notiLowReturn("Con internet", $"El servidor esta respondiendo!!"$, nid) - If B4XPages.IsInitialized Then B4XPages.MainPage.l_status.Text = "El servidor esta respondiendo!!" - Else - notiHigh("Con internet", $"El servidor NO esta respondiendo!!"$, nid, Main) - If B4XPages.IsInitialized Then B4XPages.MainPage.l_status.Text = "El servidor NO esta respondiendo!!" - End If - Next - End If -' s.logJobDoneResultados(resultado) - If resultado.Rows.Size = 0 Then DBOk = False -' Log(resultado.Rows.Size) - End If - If B4XPages.IsInitialized Then - B4XPages.MainPage.cb_internet.Checked = InternetOk - B4XPages.MainPage.cb_dbreqserver.Checked = DBReqServerOk - B4XPages.MainPage.cb_db.Checked = DBOk - End If - Job.Release - End If - -End Sub - -Sub IsConnectedToInternet As Boolean 'ignore - Dim r As Reflector - r.Target = r.GetContext - r.Target = r.RunMethod2("getSystemService", "connectivity", "java.lang.String") - r.Target = r.RunMethod("getActiveNetworkInfo") - If r.Target <> Null Then - If logger Then LogColor("isConnectedOrConnecting", Colors.green) - Return r.RunMethod("isConnectedOrConnecting") - End If - if logger then LogColor("Not connected", Colors.red) - Return False -End Sub \ No newline at end of file +' +'Sub probamosConexion +'' Log("probamos probamosConexion") +' If B4XPages.IsInitialized Then +' B4XPages.MainPage.cb_internet.Checked = False +' B4XPages.MainPage.cb_dbreqserver.Checked = False +' B4XPages.MainPage.cb_db.Checked = False +' End If +' If IsConnectedToInternet Then +' InternetOk = True +' If B4XPages.IsInitialized Then +' B4XPages.MainPage.cb_internet.Checked = True +' Dim cd1 As ColorDrawable +' cd1.Initialize(Colors.RGB(16, 141, 0), 10dip) +' B4XPages.MainPage.b_ping.Background = cd1 +' B4XPages.MainPage.b_ping.Text = "Internet Ok" +' End If +' Dim cmd As DBCommand +' notiLowReturn("Con internet", "Hay conexion a internet", nid) +' If B4XPages.IsInitialized Then B4XPages.MainPage.l_status.Text = "Hay conexion a internet!!" +' Dim cmd As DBCommand +' cmd.Initialize +' cmd.Name = "select_conexion" +' reqManager.ExecuteQuery(cmd, 0, "select_conexion", 1250) +' 'Reiniciamos el timer para cuando llamamos el Sub desde "seleccion" +' Timer1.Enabled = False +' Timer1.Interval = Interval * 1000 +' Timer1.Enabled = True +' Else +' If logger Then Log("Sin conexión a internet!!!") +' notiLowReturn("Sin internet", "NO hay conexion a internet", nid) +' If B4XPages.IsInitialized Then B4XPages.MainPage.l_status.Text = "NO hay conexion a internet!!" +' End If +' +'End Sub +' +'Sub reinicializaReqManager +' reqManager.Initialize(Me, DBReqServer) +' If logger Then Log("Inicializamos con: " & DBReqServer) +'End Sub +' +'Sub JobDone(Job As HttpJob) +'' Log("JOBDONE -- " & Job.Success) +'' Log(Job) +' If Job.Success = False Then +' If Job.JobName = "DBRequest" Then DBReqServerOk = False +' +' Dim cd1 As ColorDrawable +' cd1.Initialize(Colors.Red, 10dip) +' B4XPages.MainPage.b_ping.Background = cd1 +' B4XPages.MainPage.b_ping.Text = "DBReqServer KO" +' notiHigh("Con internet", $"El servidor ${DBReqServer} NO responde!!"$, nid, Main) +' If Job.ErrorMessage.Contains("failed to connect") Or Job.ErrorMessage.Contains("Failed to connect") Then +' ToastMessageShow("¡Hubo un error contactando al servidor, por favor revise su conexión!", True) +' End If +' Else +' If Job.JobName = "DBRequest" Then DBReqServerOk = True +' If logger Then LogColor("JobDone: '" & reqManager.HandleJob(Job).tag & "' - Registros: " & reqManager.HandleJob(Job).Rows.Size, Colors.Green) 'Mod por CHV - 211027 +' If Job.JobName = "DBRequest" Then +' Dim resultado As DBResult = reqManager.HandleJob(Job) +' If resultado.Tag = "select_conexion" Then +' For Each records() As Object In resultado.Rows +' Private valor As String = records(resultado.Columns.Get("VALOR")) +' If valor = "OK" Then +' DBOk = True +' notiLowReturn("Con internet", $"El servidor esta respondiendo!!"$, nid) +' If B4XPages.IsInitialized Then +' B4XPages.MainPage.l_status.Text = "El servidor esta respondiendo!!" +' Dim cd1 As ColorDrawable +' cd1.Initialize(Colors.RGB(16, 141, 0), 10dip) +' B4XPages.MainPage.b_ping.Background = cd1 +' B4XPages.MainPage.b_ping.Text = "Servidor Ok" +' End If +' Else +' notiHigh("Con internet", $"El servidor NO esta respondiendo!!"$, nid, Main) +' If B4XPages.IsInitialized Then +' B4XPages.MainPage.l_status.Text = "El servidor NO esta respondiendo!!" +' Dim cd1 As ColorDrawable +' cd1.Initialize(Colors.Red, 10dip) +' B4XPages.MainPage.b_ping.Background = cd1 +' B4XPages.MainPage.b_ping.Text = "Servidor KO" +' End If +' End If +' Next +' End If +'' s.logJobDoneResultados(resultado) +' If resultado.Rows.Size = 0 Then DBOk = False +'' Log(resultado.Rows.Size) +' End If +' If B4XPages.IsInitialized Then +' B4XPages.MainPage.cb_internet.Checked = InternetOk +' B4XPages.MainPage.cb_dbreqserver.Checked = DBReqServerOk +' B4XPages.MainPage.cb_db.Checked = DBOk +' End If +' Job.Release +' End If +' +'End Sub +' +'Sub IsConnectedToInternet As Boolean 'ignore +' Dim r As Reflector +' r.Target = r.GetContext +' r.Target = r.RunMethod2("getSystemService", "connectivity", "java.lang.String") +' r.Target = r.RunMethod("getActiveNetworkInfo") +' If r.Target <> Null Then +' If logger Then LogColor("isConnectedOrConnecting", Colors.green) +' Return r.RunMethod("isConnectedOrConnecting") +' End If +' If logger Then LogColor("Not connected", Colors.red) +' Return False +'End Sub diff --git a/B4A/Tester.b4a b/B4A/Tester.b4a index 1dd40e3..98a8e51 100644 --- a/B4A/Tester.b4a +++ b/B4A/Tester.b4a @@ -1,42 +1,42 @@ -Build1=Default,md.keymon.com.mx,HU2_PUBLIC -File1=login.bal -File2=logo_keymon.png -File3=MainPage.bal +Build1=Default,kmtMonitor.keymon.com.mx,HU2_PUBLIC +File1=engrane.png +File2=login.bal +File3=logo_keymon.png +File4=MainPage.bal FileGroup1=Default Group FileGroup2=Default Group FileGroup3=Default Group +FileGroup4=Default Group Group=Default Group Library1=b4xpages -Library10=okhttputils2 -Library11=phone -Library12=randomaccessfile -Library13=reflection -Library14=serial -Library15=sql -Library16=xui +Library10=runtimepermissions +Library11=sql +Library12=replyauto Library2=byteconverter -Library3=camera -Library4=compressstrings -Library5=core -Library6=fileprovider -Library7=gps -Library8=javaobject -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~~\n~)~\n~SetApplicationAttribute(android:icon, "@drawable/icon")~\n~SetApplicationAttribute(android:label, "$LABEL$")~\n~CreateResourceFromFile(Macro, Themes.LightTheme)~\n~AddApplicationText(~\n~)~\n~CreateResourceFromFile(Macro, FirebaseAnalytics.GooglePlayBase)~\n~ 'End of default text.~\n~''''' CAMBIA LA CLAVE API~\n~AddApplicationText(~\n~~\n~ ~\n~)~\n~AddApplicationText(~\n~~\n~)~\n~AddManifestText(~\n~~\n~)~\n~''CreateResourceFromFile(Macro, FirebaseAnalytics.GooglePlayBase)~\n~ 'End of default text.~\n~ ~\n~SetApplicationAttribute(android:usesCleartextTraffic, "true")~\n~ AddManifestText(~\n~~\n~)~\n~AddPermission(android.permission.ACCESS_BACKGROUND_LOCATION)~\n~AddManifestText(~\n~~\n~)~\n~AddManifestText(~\n~~\n~)~\n~AddManifestText(~\n~~\n~) 'in order to access the device non-resettable identifiers such as IMEI and serial number.~\n~~\n~'///////////////////////// FLP Y PUSH /////////////~\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~'//////////////////////////////////////////////////////~\n~~\n~'/////////////////////// App Updating ////////////////~\n~ AddManifestText(~\n~ )~\n~ AddApplicationText(~\n~ ~\n~ ~\n~ ~\n~ )~\n~ CreateResource(xml, provider_paths,~\n~ ~\n~ ~\n~ ~\n~ ~\n~ ~\n~ )~\n~AddManifestText()~\n~AddManifestText()~\n~AddManifestText()~\n~AddManifestText()~\n~~\n~AddPermission(android.permission.REQUEST_INSTALL_PACKAGES)~\n~AddPermission(android.permission.INTERNET)~\n~AddPermission(android.permission.INSTALL_PACKAGES)~\n~AddPermission(android.permission.READ_EXTERNAL_STORAGE)~\n~AddPermission(android.permission.WRITE_EXTERNAL_STORAGE)~\n~AddPermission(android.permission.READ_PHONE_STATE)~\n~AddPermission(android.permission.WAKE_LOCK)~\n~CreateResourceFromFile(Macro, JhsIceZxing1.CaturePortrait)~\n~AddPermission("android.permission.MANAGE_EXTERNAL_STORAGE")~\n~SetApplicationAttribute(android:largeHeap, "true")~\n~AddPermission("android.permission.MANAGE_EXTERNAL_STORAGE")~\n~ +Library3=core +Library4=fusedlocationprovider +Library5=gps +Library6=okhttputils2 +Library7=phone +Library8=randomaccessfile +Library9=reflection +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~~\n~)~\n~SetApplicationAttribute(android:icon, "@drawable/icon")~\n~SetApplicationAttribute(android:label, "$LABEL$")~\n~CreateResourceFromFile(Macro, Themes.LightTheme)~\n~CreateResourceFromFile(Macro, FirebaseAnalytics.GooglePlayBase)~\n~ 'End of default text.~\n~''''' CAMBIA LA CLAVE API~\n~AddApplicationText(~\n~~\n~ ~\n~)~\n~AddApplicationText(~\n~~\n~)~\n~AddManifestText(~\n~~\n~)~\n~ 'End of default text.~\n~ ~\n~SetApplicationAttribute(android:usesCleartextTraffic, "true")~\n~AddManifestText()~\n~AddPermission(android.permission.ACCESS_BACKGROUND_LOCATION)~\n~AddManifestText()~\n~AddManifestText() 'in order to access the device non-resettable identifiers such as IMEI and serial number.~\n~AddManifestText()~\n~AddManifestText()~\n~AddManifestText()~\n~AddManifestText()~\n~AddPermission(android.permission.REQUEST_INSTALL_PACKAGES)~\n~AddPermission(android.permission.INTERNET)~\n~AddPermission(android.permission.INSTALL_PACKAGES)~\n~AddPermission(android.permission.READ_EXTERNAL_STORAGE)~\n~AddPermission(android.permission.WRITE_EXTERNAL_STORAGE)~\n~AddPermission(android.permission.READ_PHONE_STATE)~\n~AddPermission(android.permission.WAKE_LOCK)~\n~AddPermission("android.permission.MANAGE_EXTERNAL_STORAGE")~\n~SetApplicationAttribute(android:largeHeap, "true")~\n~~\n~AddManifestText()~\n~AddPermission(android.permission.INTERNET)~\n~SetApplicationAttribute(android:allowBackup, "false")~\n~AddApplicationText(~\n~ ~\n~) Module1=B4XMainPage Module2=BatteryUtilities Module3=C_Subs Module4=DBRequestManager -Module5=Starter -NumberOfFiles=3 -NumberOfLibraries=16 -NumberOfModules=5 +Module5=Monitor +Module6=NotificationService +Module7=Starter +NumberOfFiles=4 +NumberOfLibraries=12 +NumberOfModules=7 Version=12.2 @EndOfDesignText@ #Region Project Attributes - #ApplicationLabel: Tester + #ApplicationLabel: Monitor Keymon #VersionCode: 1 - #VersionName: 3.09.04 + #VersionName: 3.09.09 'SupportedOrientations possible values: unspecified, landscape or portrait. #SupportedOrientations: portrait #CanInstallToExternalStorage: False @@ -60,7 +60,7 @@ Sub Globals Type CameraSize (Width As Int, Height As Int) End Sub -Sub Activity_Create(FirstTime As Boolean) +Sub Activity_Create(FirstTime As Boolean) 'ignore Dim pm As B4XPagesManager pm.Initialize(Activity) End Sub diff --git a/B4A/Tracker.bas b/B4A/Tracker.bas index 7cd70fc..6de1078 100644 --- a/B4A/Tracker.bas +++ b/B4A/Tracker.bas @@ -2,7 +2,7 @@ Group=Default Group ModulesStructureVersion=1 Type=Service -Version=10.2 +Version=11 @EndOfDesignText@ #Region Service Attributes #StartAtBoot: True @@ -142,7 +142,7 @@ End Sub Sub dameUltimaUbicacionConocida If FLP.GetLastKnownLocation.IsInitialized Then 'Mandamos ultima ubicacion guardada ' If Main.logger Then Log("Mandamos UUC : "&formatoFecha(FLP.GetLastKnownLocation.Time)) - If Starter.Logger Then LogColor($"Mandamos UUC "${Subs.fechaKMT(FLP.GetLastKnownLocation.Time)}|Acc:$0.2{FLP.GetLastKnownLocation.Accuracy}|$0.8{FLP.GetLastKnownLocation.Latitude}|$0.8{FLP.GetLastKnownLocation.Longitude}|Spd:$0.2{FLP.GetLastKnownLocation.Speed}|"$, Colors.RGB(255,112,35)) +' If Starter.Logger Then LogColor($"Mandamos UUC "${Subs.fechaKMT(FLP.GetLastKnownLocation.Time)}|Acc:$0.2{FLP.GetLastKnownLocation.Accuracy}|$0.8{FLP.GetLastKnownLocation.Latitude}|$0.8{FLP.GetLastKnownLocation.Longitude}|Spd:$0.2{FLP.GetLastKnownLocation.Speed}|"$, Colors.RGB(255,112,35)) Dim coords As String = FLP.GetLastKnownLocation.Latitude&","&FLP.GetLastKnownLocation.Longitude&","&formatoFecha(FLP.GetLastKnownLocation.Time) ' CallSubDelayed2(FirebaseMessaging,"mandamosLoc",coords) ' Subs.mandamosLoc(coords) @@ -160,8 +160,8 @@ End Sub Sub flp_LocationChanged (Location1 As Location) ' ToastMessageShow("Loc changed", False) ' Log($"Loc changed:${Location1.Longitude},${Location1.Latitude}"$) - B4XPages.MainPage.lat_gps = Location1.Latitude - B4XPages.MainPage.lon_gps = Location1.Longitude +' B4XPages.MainPage.lat_gps = Location1.Latitude +' B4XPages.MainPage.lon_gps = Location1.Longitude UUGCoords = Location1 ' Log("SmallestDisplacement="&actualLR.GetSmallestDisplacement) ' If DateTime.Now > LastUpdateTime + 10 * DateTime.TicksPerSecond Then @@ -174,13 +174,13 @@ Sub flp_LocationChanged (Location1 As Location) DateTime.DateFormat = "MM/dd/yyyy" sDate=DateTime.Date(DateTime.Now) sTime=DateTime.Time(DateTime.Now) - If Not(B4XPages.MainPage.skmt.IsInitialized) Then B4XPages.MainPage.skmt.Initialize(Starter.ruta,"kmt.db", True) - Try - B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO HIST_GPS (HGDATE, HGLAT, HGLON) VALUES(?,?,?) ", Array As Object (sDate & sTime, B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps)) - B4XPages.MainPage.skmt.ExecNonQuery("DELETE FROM HIST_GPS") - Catch - LogColor(LastException, Colors.Red) - End Try +' If Not(B4XPages.MainPage.skmt.IsInitialized) Then B4XPages.MainPage.skmt.Initialize(Starter.ruta,"kmt.db", True) +' Try +' B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO HIST_GPS (HGDATE, HGLAT, HGLON) VALUES(?,?,?) ", Array As Object (sDate & sTime, B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps)) +' B4XPages.MainPage.skmt.ExecNonQuery("DELETE FROM HIST_GPS") +' Catch +' LogColor(LastException, Colors.Red) +' End Try '/////// Dim coords As String = Location1.Latitude&","&Location1.Longitude&","&formatoFecha(Location1.Time) ' Log("Loc changed : "&Location1.Latitude&","&Location1.Longitude&"|"&B4XPages.MainPage.usuario&"|") @@ -225,46 +225,46 @@ End Sub 'Revisamos que el FLP (FusedLocationProvider) este inicializado y activo Sub revisaFLP 'ignore - LogColor("**** **** Revisamos FLP **** ****", Colors.RGB(78,0,227)) - Private todoBienFLP As Boolean = True - Try - If Not(FLP.IsInitialized) Then - Subs.log2DB("revisaFLP: No esta inicializado ... 'Reinicializando FLP'") - FLP.Initialize("flp") - todoBienFLP = False - End If - Catch - LogColor("If Not(Tracker.FLP.IsInitialized) --> "&LastException, Colors.Red) - End Try - Try - If FLP.IsInitialized Then - Try - If Not(FLP.IsConnected) Then - Subs.log2DB("revisaFLP: No esta conectado ... 'Reconectando FLP'") - ' Tracker.FLP.Connect - StartFLP - todoBienFLP = False - End If - Catch - LogColor("If Not(Tracker.FLP.IsConnected) --> "&LastException, Colors.Red) - End Try - Try - If FLP.IsConnected And _ - FLP.GetLastKnownLocation.IsInitialized And _ - FLP.GetLastKnownLocation.DistanceTo(UUGCoords) > 500 Then - Subs.log2DB("revisaFLP: 'No se esta actualizando, lo reiniciamos ...'") - StartService(Me) - todoBienFLP = False - End If - Catch - LogColor("If FLP.IsConnectctd and FLP.getLKL.IsInitialized --> "&LastException, Colors.Red) - End Try - End If - If todoBienFLP Then LogColor(" +++ +++ Sin errores en FLP", Colors.Green) - Catch - LogColor("If Tracker.FLP.IsInitialized --> "&LastException, Colors.Red) - End Try - ' revisar hora de lastKnownlocation y si es mayor de 10 minutos llamar StartFLP +' LogColor("**** **** Revisamos FLP **** ****", Colors.RGB(78,0,227)) +' Private todoBienFLP As Boolean = True +' Try +' If Not(FLP.IsInitialized) Then +'' Subs.log2DB("revisaFLP: No esta inicializado ... 'Reinicializando FLP'") +' FLP.Initialize("flp") +' todoBienFLP = False +' End If +' Catch +' LogColor("If Not(Tracker.FLP.IsInitialized) --> "&LastException, Colors.Red) +' End Try +' Try +' If FLP.IsInitialized Then +' Try +' If Not(FLP.IsConnected) Then +'' Subs.log2DB("revisaFLP: No esta conectado ... 'Reconectando FLP'") +' ' Tracker.FLP.Connect +' StartFLP +' todoBienFLP = False +' End If +' Catch +' LogColor("If Not(Tracker.FLP.IsConnected) --> "&LastException, Colors.Red) +' End Try +' Try +' If FLP.IsConnected And _ +' FLP.GetLastKnownLocation.IsInitialized And _ +' FLP.GetLastKnownLocation.DistanceTo(UUGCoords) > 500 Then +'' Subs.log2DB("revisaFLP: 'No se esta actualizando, lo reiniciamos ...'") +' StartService(Me) +' todoBienFLP = False +' End If +' Catch +' LogColor("If FLP.IsConnectctd and FLP.getLKL.IsInitialized --> "&LastException, Colors.Red) +' End Try +' End If +' If todoBienFLP Then LogColor(" +++ +++ Sin errores en FLP", Colors.Green) +' Catch +' LogColor("If Tracker.FLP.IsInitialized --> "&LastException, Colors.Red) +' End Try +' ' revisar hora de lastKnownlocation y si es mayor de 10 minutos llamar StartFLP End Sub 'Compara la UUG (Ultima Ubicacion Guardada) con FLP.LastKnowLocation y si @@ -277,11 +277,11 @@ Sub revisaUUG 'ignore If FLP.GetLastKnownLocation.IsInitialized Then ' Dim x As Location = FLP.GetLastKnownLocation Dim daa As Int = UUGCoords.DistanceTo(FLP.GetLastKnownLocation) 'Distancia de la UUG a la actual de Tracker.FLP.GetLastKnownLocation - If Starter.Logger Then LogColor($"**** UUC "${Subs.fechaKMT(FLP.GetLastKnownLocation.Time)}|$0.2{FLP.GetLastKnownLocation.Accuracy}|$0.8{FLP.GetLastKnownLocation.Latitude}|$0.8{FLP.GetLastKnownLocation.Longitude}|$0.2{FLP.GetLastKnownLocation.Speed}|"$, Colors.RGB(255,112,35)) - If daa > 40 And FLP.GetLastKnownLocation.Accuracy < 35 Then 'Si la distancia de la ubicacion anterior es mayor de XX y la precision es menor de XX, la guardamos ... - B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO RUTA_GPS(fecha, lat, lon) VALUES (?,?,?)", Array As Object (Subs.fechaKMT(FLP.GetLastKnownLocation.Time),FLP.GetLastKnownLocation.Latitude,FLP.GetLastKnownLocation.Longitude)) - If Starter.Logger Then Log("++++ Distancia a anterior="&daa&"|"&"Precision="&FLP.GetLastKnownLocation.Accuracy) - End If +' If Starter.Logger Then LogColor($"**** UUC "${Subs.fechaKMT(FLP.GetLastKnownLocation.Time)}|$0.2{FLP.GetLastKnownLocation.Accuracy}|$0.8{FLP.GetLastKnownLocation.Latitude}|$0.8{FLP.GetLastKnownLocation.Longitude}|$0.2{FLP.GetLastKnownLocation.Speed}|"$, Colors.RGB(255,112,35)) +' If daa > 40 And FLP.GetLastKnownLocation.Accuracy < 35 Then 'Si la distancia de la ubicacion anterior es mayor de XX y la precision es menor de XX, la guardamos ... +' B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO RUTA_GPS(fecha, lat, lon) VALUES (?,?,?)", Array As Object (Subs.fechaKMT(FLP.GetLastKnownLocation.Time),FLP.GetLastKnownLocation.Latitude,FLP.GetLastKnownLocation.Longitude)) +' If Starter.Logger Then Log("++++ Distancia a anterior="&daa&"|"&"Precision="&FLP.GetLastKnownLocation.Accuracy) +' End If UUGCoords = FLP.GetLastKnownLocation End If Catch diff --git a/B4A/monitor.bas b/B4A/monitor.bas new file mode 100644 index 0000000..8ce285c --- /dev/null +++ b/B4A/monitor.bas @@ -0,0 +1,171 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=Service +Version=12.2 +@EndOfDesignText@ +#Region Service Attributes + #StartAtBoot: 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 reqManager As DBRequestManager +' Dim DBReqServer As String = "http://keymon.lat:1782" +' Dim skmt As SQL + Dim Timer1 As Timer + Private lock As PhoneWakeState + Dim Interval As Int + Dim s As C_Subs + Dim nid As Int = 51043 + Dim monitorActivo As Boolean = True + Dim InternetOk As Boolean = True + Dim DBReqServerOk As Boolean = True + Dim DBOk As Boolean = True + Dim logger As Boolean = True + Dim timeout As Int +End Sub + +Sub Service_Create + s.Initialize + Interval = s.traeIntervaloDeBD + timeout = s.traeTimeoutDeBD + Timer1.Initialize("Timer1", Interval * 1000) + Timer1.Enabled = True + #if not(DEBUG) + logger = False + #end if + lock.PartialLock +' probamosConexion +End Sub + +Sub Service_Start (StartingIntent As Intent) + Service.StopAutomaticForeground 'Call this when the background task completes (if there is one) + Service.StartForeground(nid, s.CreateNotification("...")) + StartServiceAt(Me, DateTime.Now + 1 * DateTime.TicksPerMinute, True) + reqManager.Initialize(Me, Starter.DBReqServer) + Timer1_Tick + If logger Then LogColor("*************** Monitor Iniciado 👍🏽 **********", Colors.red) +End Sub + +Sub Service_Destroy + +End Sub + +Sub Timer1_Tick +' Log("Next run " & DateTime.Time(DateTime.Now + Interval * 1000)) + DateTime.DateFormat = "dd/MM HH:mm:ss" + If B4XPages.IsInitialized Then B4XPages.MainPage.l_ultimoPing.Text = $"Último ping: ${DateTime.Date(DateTime.now)}"$ + If monitorActivo Then probamosConexion +End Sub + +Sub probamosConexion + If logger Then Log("probamos probamosConexion") + If B4XPages.IsInitialized Then + B4XPages.MainPage.cb_internet.Checked = False + B4XPages.MainPage.cb_dbreqserver.Checked = False + B4XPages.MainPage.cb_db.Checked = False + End If + If IsConnectedToInternet Then + InternetOk = True + If B4XPages.IsInitialized Then + B4XPages.MainPage.cb_internet.Checked = True + Dim cd1 As ColorDrawable + cd1.Initialize(Colors.RGB(16, 141, 0), 10dip) + B4XPages.MainPage.b_ping.Background = cd1 + B4XPages.MainPage.b_ping.Text = "Internet Ok" + End If + Dim cmd As DBCommand + s.notiLowReturn("Con internet", "Hay conexion a internet", nid) + If B4XPages.IsInitialized Then B4XPages.MainPage.l_status.Text = "Hay conexion a internet!!" + Dim cmd As DBCommand + cmd.Initialize + cmd.Name = "select_conexion" + reqManager.ExecuteQuery(cmd, 0, "select_conexion", timeout) + 'Reiniciamos el timer para cuando llamamos el Sub desde "seleccion" + Timer1.Enabled = False + Timer1.Interval = Interval * 1000 + Timer1.Enabled = True + Else + If logger Then Log("Sin conexión a internet!!!") + s.notiLowReturn("Sin internet", "NO hay conexion a internet", nid) + If B4XPages.IsInitialized Then B4XPages.MainPage.l_status.Text = "NO hay conexion a internet!!" + End If + +End Sub + +Sub reinicializaReqManager 'ignore + reqManager.Initialize(Me, Starter.DBReqServer) + If logger Then Log("Inicializamos con: " & Starter.DBReqServer) +End Sub + +Sub JobDone(Job As HttpJob) +' Log("JOBDONE -- " & Job.Success) +' Log(Job) + If Job.Success = False Then + If Job.JobName = "DBRequest" Then DBReqServerOk = False + + Dim cd1 As ColorDrawable + cd1.Initialize(Colors.Red, 10dip) + B4XPages.MainPage.b_ping.Background = cd1 + B4XPages.MainPage.b_ping.Text = "DBReqServer KO" + s.notiHigh("Con internet", $"El servidor ${Starter.DBReqServer} NO responde!!"$, nid, Main) + If Job.ErrorMessage.Contains("failed to connect") Or Job.ErrorMessage.Contains("Failed to connect") Then + ToastMessageShow("¡Hubo un error contactando al servidor, por favor revise su conexión!", True) + End If + Else + If Job.JobName = "DBRequest" Then DBReqServerOk = True + If logger Then LogColor("JobDone: '" & reqManager.HandleJob(Job).tag & "' - Registros: " & reqManager.HandleJob(Job).Rows.Size, Colors.Green) 'Mod por CHV - 211027 + If Job.JobName = "DBRequest" Then + Dim resultado As DBResult = reqManager.HandleJob(Job) + If resultado.Tag = "select_conexion" Then + For Each records() As Object In resultado.Rows + Private valor As String = records(resultado.Columns.Get("VALOR")) + If valor = "OK" Then + DBOk = True + s.notiLowReturn("Con internet", $"El servidor esta respondiendo!!"$, nid) + If B4XPages.IsInitialized Then + B4XPages.MainPage.l_status.Text = "El servidor esta respondiendo!!" + Dim cd1 As ColorDrawable + cd1.Initialize(Colors.RGB(16, 141, 0), 10dip) + B4XPages.MainPage.b_ping.Background = cd1 + B4XPages.MainPage.b_ping.Text = "Servidor Ok" + End If + Else + s.notiHigh("Con internet", $"El servidor NO esta respondiendo!!"$, nid, Main) + If B4XPages.IsInitialized Then + B4XPages.MainPage.l_status.Text = "El servidor NO esta respondiendo!!" + Dim cd1 As ColorDrawable + cd1.Initialize(Colors.Red, 10dip) + B4XPages.MainPage.b_ping.Background = cd1 + B4XPages.MainPage.b_ping.Text = "Servidor KO" + End If + End If + Next + End If +' s.logJobDoneResultados(resultado) + If resultado.Rows.Size = 0 Then DBOk = False +' Log(resultado.Rows.Size) + End If + If B4XPages.IsInitialized Then + B4XPages.MainPage.cb_internet.Checked = InternetOk + B4XPages.MainPage.cb_dbreqserver.Checked = DBReqServerOk + B4XPages.MainPage.cb_db.Checked = DBOk + End If + Job.Release + End If +End Sub + +Sub IsConnectedToInternet As Boolean 'ignore + Dim r As Reflector + r.Target = r.GetContext + r.Target = r.RunMethod2("getSystemService", "connectivity", "java.lang.String") + r.Target = r.RunMethod("getActiveNetworkInfo") + If r.Target <> Null Then + If logger Then LogColor("isConnectedOrConnecting", Colors.green) + Return r.RunMethod("isConnectedOrConnecting") + End If + If logger Then LogColor("Not connected", Colors.red) + Return False +End Sub