09/09/23 - Panel de configuración y servicio al arranque

Se agregó´un panel para cambiar algunos parametros de la aplicación y se agregó´un servicio para que el monitor arranque junto con el dispositivo, para esto es necesario darle permisos para accesar las notificaciones del sistema.
This commit is contained in:
2023-09-10 00:28:33 -06:00
parent afe26d8653
commit d342c85e15
11 changed files with 744 additions and 432 deletions

View File

@@ -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