diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..a3f49d9 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,16 @@ +# Auto detect text files and perform LF normalization +* text=auto + +# linguist-language +*.b4a linguist-language=B4X +*.b4i linguist-language=B4X +*.b4j linguist-language=B4X +*.b4r linguist-language=B4X +*.bas linguist-language=B4X + +# linguist-detectable +*.b4a linguist-detectable=true +*.b4i linguist-detectable=true +*.b4j linguist-detectable=true +*.b4r linguist-detectable=true +*.bas linguist-detectable=true \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..af94e9d --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +**/Objects +**/AutoBackups \ No newline at end of file diff --git a/B4A/C_Principal.bas b/B4A/C_Principal.bas new file mode 100644 index 0000000..c8a3672 --- /dev/null +++ b/B4A/C_Principal.bas @@ -0,0 +1,24 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=12.8 +@EndOfDesignText@ +Sub Class_Globals + Private Root As B4XView 'ignore + Private xui As XUI 'ignore +End Sub + +'You can add more parameters here. +Public Sub Initialize As Object + Return Me +End Sub + +'This event will be called once, before the page becomes visible. +Private Sub B4XPage_Created (Root1 As B4XView) + Root = Root1 + 'load the layout to Root + +End Sub + +'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage. \ No newline at end of file diff --git a/B4A/DBRequestManager.bas b/B4A/DBRequestManager.bas new file mode 100644 index 0000000..1a8b358 --- /dev/null +++ b/B4A/DBRequestManager.bas @@ -0,0 +1,272 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=6.8 +@EndOfDesignText@ +'Necesita la libreria RandomAccessFile + +'Class module +Sub Class_Globals + Private mTarget As Object + Type DBResult (Tag As Object, Columns As Map, Rows As List) + Type DBCommand (Name As String, Parameters() As Object) + Private link As String + Private bc As ByteConverter + Private T_NULL = 0, T_STRING = 1, T_SHORT = 2, T_INT = 3, T_LONG = 4, T_FLOAT = 5 _ + ,T_DOUBLE = 6, T_BOOLEAN = 7, T_BLOB = 8 As Byte + Private VERSION As Float = 0.9 + Private tempArray(1) As Object + Dim jobTagAnterior As String = "" 'Mod por CHV - 211027 +End Sub + +'Target - The module that handles JobDone (usually Me). +'ConnectorLink - URL of the Java server. +Public Sub Initialize (Target As Object, ConnectorLink As String) + mTarget = Target + link = ConnectorLink +End Sub + +'Sends a query request. +'Command - Query name and parameters. +'Limit - Maximum rows to return or 0 for no limit. +'Tag - An object that will be returned in the result. +Public Sub ExecuteQuery(Command As DBCommand, Limit As Int, Tag As Object) + Dim j As HttpJob + Dim ms As OutputStream + Dim out2 As OutputStream = StartJob(j,ms, Tag) + + WriteObject(Command.Name, out2) + WriteInt(Limit, out2) + WriteList(Command.Parameters, out2) + out2.Close + j.PostBytes(link & "?method=query", ms.ToBytesArray) +End Sub + +'Executes a batch of (non-select) commands. +'ListOfCommands - List of the commands that will be executes. +'Tag - An object that will be returned in the result. +Public Sub ExecuteBatch(ListOfCommands As List, Tag As Object) + Dim j As HttpJob + Dim ms As OutputStream + Dim out2 As OutputStream = StartJob(j,ms, Tag) + WriteInt(ListOfCommands.Size, out2) + For Each Command As DBCommand In ListOfCommands + WriteObject(Command.Name, out2) + WriteList(Command.Parameters, out2) + Next + out2.Close + j.PostBytes(link & "?method=batch", ms.ToBytesArray) +End Sub + +'Similar to ExecuteBatch. Sends a single command. +Public Sub ExecuteCommand(Command As DBCommand, Tag As Object) + ExecuteBatch(Array As DBCommand(Command), Tag) +End Sub + +Private Sub StartJob(j As HttpJob, MemoryStream As OutputStream, Tag As Object) As OutputStream + j.Initialize("DBRequest", mTarget) + j.Tag = Tag + MemoryStream.InitializeToBytesArray(0) + Dim compress As CompressedStreams + Dim out As OutputStream = compress.WrapOutputStream(MemoryStream, "gzip") + WriteObject(VERSION, out) + Return out +End Sub + +Private Sub WriteList(Parameters As List, out As OutputStream) + Dim data() As Byte + If Parameters = Null Or Parameters.IsInitialized = False Then + Dim Parameters As List + Parameters.Initialize + End If + data = bc.IntsToBytes(Array As Int(Parameters.Size)) + out.WriteBytes(data, 0, data.Length) + For Each o As Object In Parameters + WriteObject(o, out) + Next +End Sub + +Private Sub WriteObject(o As Object, out As OutputStream) + Dim data() As Byte + tempArray(0) = o + If tempArray(0) = Null Then + out.WriteBytes(Array As Byte(T_NULL), 0, 1) + Else If tempArray(0) Is Short Then + out.WriteBytes(Array As Byte(T_SHORT), 0, 1) + data = bc.ShortsToBytes(Array As Short(o)) + Else If tempArray(0) Is Int Then + out.WriteBytes(Array As Byte(T_INT), 0, 1) + data = bc.IntsToBytes(Array As Int(o)) + Else If tempArray(0) Is Float Then + out.WriteBytes(Array As Byte(T_FLOAT), 0, 1) + data = bc.FloatsToBytes(Array As Float(o)) + Else If tempArray(0) Is Double Then + out.WriteBytes(Array As Byte(T_DOUBLE), 0, 1) + data = bc.DoublesToBytes(Array As Double(o)) + Else If tempArray(0) Is Long Then + out.WriteBytes(Array As Byte(T_LONG), 0, 1) + data = bc.LongsToBytes(Array As Long(o)) + Else If tempArray(0) Is Boolean Then + out.WriteBytes(Array As Byte(T_BOOLEAN), 0, 1) + Dim b As Boolean = 0 + Dim data(1) As Byte + If b Then data(0) = 1 Else data(0) = 0 + Else If GetType(tempArray(0)) = "[B" Then + data = o + out.WriteBytes(Array As Byte(T_BLOB), 0, 1) + WriteInt(data.Length, out) + Else 'If o Is String Then (treat all other values as string) + out.WriteBytes(Array As Byte(T_STRING), 0, 1) + data = bc.StringToBytes(o, "UTF8") + WriteInt(data.Length, out) + End If + If data.Length > 0 Then out.WriteBytes(data, 0, data.Length) +End Sub + +Private Sub ReadObject(In As InputStream) As Object + Dim data(1) As Byte + In.ReadBytes(data, 0, 1) + Select data(0) + Case T_NULL + Return Null + Case T_SHORT + Dim data(2) As Byte + Return bc.ShortsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_INT + Dim data(4) As Byte + Return bc.IntsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_LONG + Dim data(8) As Byte + Return bc.LongsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_FLOAT + Dim data(4) As Byte + Return bc.FloatsFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_DOUBLE + Dim data(8) As Byte + Return bc.DoublesFromBytes(ReadBytesFully(In, data, data.Length))(0) + Case T_BOOLEAN + Dim b As Byte = ReadByte(In) + Return b = 1 + Case T_BLOB + Dim len As Int = ReadInt(In) + Dim data(len) As Byte + Return ReadBytesFully(In, data, data.Length) + Case Else + Dim len As Int = ReadInt(In) + Dim data(len) As Byte + ReadBytesFully(In, data, data.Length) + Return BytesToString(data, 0, data.Length, "UTF8") + End Select +End Sub + +Private Sub ReadBytesFully(In As InputStream, Data() As Byte, Len As Int) As Byte() + Dim count = 0, read As Int + Do While count < Len And read > -1 + read = In.ReadBytes(Data, count, Len - count) + count = count + read + Loop + Return Data +End Sub + +Private Sub WriteInt(i As Int, out As OutputStream) + Dim data() As Byte + data = bc.IntsToBytes(Array As Int(i)) + out.WriteBytes(data, 0, data.Length) +End Sub + +Private Sub ReadInt(In As InputStream) As Int + Dim data(4) As Byte + Return bc.IntsFromBytes(ReadBytesFully(In, data, data.Length))(0) +End Sub + +Private Sub ReadByte(In As InputStream) As Byte + Dim data(1) As Byte + In.ReadBytes(data, 0, 1) + Return data(0) +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 In As InputStream = Job.GetInputStream + Dim cs As CompressedStreams + In = cs.WrapInputStream(In, "gzip") + Dim serverVersion As Float = ReadObject(In) 'ignore + Dim method As String = ReadObject(In) + Dim table As DBResult + table.Initialize + table.Columns.Initialize + table.rows.Initialize + table.Tag = Job.Tag + If jobTagAnterior <> Job.Tag Then LogColor("HandleJob: '"&Job.Tag&"'", Colors.Blue) 'Mod por CHV - 211023 + jobTagAnterior = Job.Tag 'Mod por CHV - 211023 + If method = "query" Then + Dim numberOfColumns As Int = ReadInt(In) + For i = 0 To numberOfColumns - 1 + table.Columns.Put(ReadObject(In), i) + Next + Do While ReadByte(In) = 1 + Dim rowObjects(numberOfColumns) As Object + table.rows.Add(rowObjects) + For col = 0 To numberOfColumns - 1 + Dim o As Object = ReadObject(In) + rowObjects(col) = o + Next + Loop + Else If method = "batch" Then + table.Columns.Put("AffectedRows", 0) + Dim rows As Int = ReadInt(In) + For i = 0 To rows - 1 + table.rows.Add(Array As Object(ReadInt(In))) + Next + End If + In.Close +' Log("HandleJob: " & (DateTime.Now - start)) + Return table +End Sub +'Reads a file and returns the file as a bytes array. +Public Sub FileToBytes(Dir As String, FileName As String) As Byte() + Dim out As OutputStream + out.InitializeToBytesArray(0) + Dim In As InputStream = File.OpenInput(Dir, FileName) + File.Copy2(In, out) + out.Close + Return out.ToBytesArray +End Sub +'Converts an image to a bytes array (for BLOB fields). +Public Sub ImageToBytes(Image As Bitmap) As Byte() + Dim out As OutputStream + out.InitializeToBytesArray(0) + Image.WriteToStream(out, 100, "JPEG") + out.Close + Return out.ToBytesArray +End Sub +'Converts a bytes array to an image (for BLOB fields). +Public Sub BytesToImage(bytes() As Byte) As Bitmap + Dim In As InputStream + In.InitializeFromBytesArray(bytes, 0, bytes.Length) + Dim bmp As Bitmap + bmp.Initialize2(In) + Return bmp +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) + Dim sb As StringBuilder + sb.Initialize + For Each col In Table.Columns.Keys + sb.Append(col).Append(TAB) + Next + Log(sb.ToString) + For Each row() As Object In Table.Rows + Dim sb As StringBuilder + sb.Initialize + For Each record As Object In row + sb.Append(record).Append(TAB) + Next + ToastMessageShow(sb.ToString, True) + Next +End Sub + + \ No newline at end of file diff --git a/B4A/EscPosPrinter.bas b/B4A/EscPosPrinter.bas new file mode 100644 index 0000000..f0a9536 --- /dev/null +++ b/B4A/EscPosPrinter.bas @@ -0,0 +1,1158 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=9.3 +@EndOfDesignText@ +#IgnoreWarnings: 9 +' 9 = unused variable + +Sub Class_Globals + ' 1.0 Initial version + ' 2.0 Added FeedPaper, changed many WriteString(.." & Chr(number)) instances to WriteBytes(params) + ' This is to avoid Unicode code page transformations on some numbers > 32 + ' Added PrintAndFeedPaper, setRelativePrintPosn, + ' Added user defined characters, DefineCustomCharacter, DeleteCustomCharacter and setUseCustomCharacters + ' Addedhelper methods CreateCustomCharacter, CreateLine, CreateBox and CreateCircle + Private Version As Double = 2.0 ' Printer class version + + Type AnImage(Width As Int, Height As Int, Data() As Byte) + + Private EventName As String 'ignore + Private CallBack As Object 'ignore + + Private Serial1 As Serial + Private Astream As AsyncStreams + Private Connected As Boolean + Private ConnectedError As String + + Dim ESC As String = Chr(27) + Dim FS As String = Chr(28) + Dim GS As String = Chr(29) + + 'Bold and underline don't work well in reversed text + Dim UNREVERSE As String = GS & "B" & Chr(0) + Dim REVERSE As String = GS & "B" & Chr(1) + + ' Character orientation. Print upside down from right margin + Dim UNINVERT As String = ESC & "{0" + Dim INVERT As String = ESC & "{1" + + ' Character rotation clockwise. Not much use without also reversing the printed character sequence + Dim UNROTATE As String = ESC & "V0" + Dim ROTATE As String = ESC & "V1" + + ' Horizontal tab + Dim HT As String = Chr(9) + + ' Character underline + Dim ULINE0 As String = ESC & "-0" + Dim ULINE1 As String = ESC & "-1" + Dim ULINE2 As String = ESC & "-2" + + ' Character emphasis + Dim BOLD As String = ESC & "E1" + Dim NOBOLD As String = ESC & "E0" + + ' Character height and width + Dim SINGLE As String = GS & "!" & Chr(0x00) + Dim HIGH As String = GS & "!" & Chr(0x01) + Dim WIDE As String = GS & "!" & Chr(0x10) + Dim HIGHWIDE As String = GS & "!" & Chr(0x11) + + ' Default settings + Private LEFTJUSTIFY As String = ESC & "a0" + Private LINEDEFAULT As String = ESC & "2" + Private LINSET0 As String = ESC & "$" & Chr(0x0) & Chr(0x0) + Private LMARGIN0 As String = GS & "L" & Chr(0x0) & Chr(0x0) + Private WIDTH0 As String = GS & "W" & Chr(0xff) & Chr(0xff) + Private CHARSPACING0 As String = ESC & " " & Chr(0) + Private CHARFONT0 As String = ESC & "M" & Chr(0) + Dim DEFAULTS As String = CHARSPACING0 & CHARFONT0 & LMARGIN0 & WIDTH0 & LINSET0 & LINEDEFAULT & LEFTJUSTIFY _ + & UNINVERT & UNROTATE & UNREVERSE & NOBOLD & ULINE0 + +End Sub + +'********** +'PUBLIC API +'********** + +'Initialize the object with the parent and event name +Public Sub Initialize(vCallback As Object, vEventName As String) + EventName = vEventName + CallBack = vCallback + Serial1.Initialize("Serial1") + Connected = False + ConnectedError = "" +End Sub + +' Returns any error raised by the last attempt to connect a printer +Public Sub ConnectedErrorMsg As String + Return ConnectedError +End Sub + +' Returns whether a printer is connected or not +Public Sub IsConnected As Boolean + Return Connected +End Sub + +' Returns whether Bluetooth is on or off +Public Sub IsBluetoothOn As Boolean + Return Serial1.IsEnabled +End Sub + +' Ask the user to connect to a printer and return whether she tried or not +' If True then a subsequent Connected event will indicate success or failure +Public Sub Connect As Boolean + 'leos +' Serial1.Connect("88:6B:0F:3E:53:9E") +' Return True + Try + If Starter.MAC_IMPRESORA = "0" Then + Dim PairedDevices As Map + PairedDevices = Serial1.GetPairedDevices + Dim l As List + l.Initialize + Log("aqui 1") + For i = 0 To PairedDevices.Size - 1 + l.Add(PairedDevices.GetKeyAt(i)) + Log("aqui 2") + DisConnect + Next + Dim Res As Int + Res = InputList(l, "Choose a printer", -1) 'show list with paired devices 'ignore + If Res <> DialogResponse.CANCEL Then + Serial1.Connect(PairedDevices.Get(l.Get(Res))) 'convert the name to mac address + 'Msgbox(PairedDevices.Get(l.Get(Res)),"mac") + Starter.mac_impresora = PairedDevices.Get(l.Get(Res)) + Return True + DisConnect + Log("aqui 3") + End If + Log("aqui 4") + Return False + Else + Serial1.Connect(Starter.mac_impresora) + ' Starter.mac_impresora = colonia.MAC_IMPRESORA + Return True + DisConnect + Log("aqui 5") + End If + Catch + Log(LastException) + Return False + End Try +End Sub + + +' Disconnect the printer +Public Sub DisConnect + Serial1.Disconnect + Connected = False +End Sub + +' Reset the printer to the power on state +Public Sub Reset + WriteString(ESC & "@") +End Sub + +'-------------- +' Text Commands +'-------------- + +' Print any outstanding characters then feed the paper the specified number of units of 0.125mm +' This is similar to changing LineSpacing before sending CRLF but this has a one off effect +' A full character height is always fed even if units = 0. Units defines the excess over this minimum +Public Sub PrintAndFeedPaper(units As Int) + WriteString(ESC & "J") + Dim params(1) As Byte + params(0) = units + WriteBytes(params) +End Sub + +' Set the distance between characters +Public Sub setCharacterSpacing(spacing As Int) + WriteString(ESC & " ") + Dim params(1) As Byte + params(0) = spacing + WriteBytes(params) +End Sub + +' Set the left inset of the next line to be printed +' Automatically resets to 0 for the following line +' inset is specified in units of 0.125mm +Public Sub setLeftInset(inset As Int) + Dim dh As Int = inset / 256 + Dim dl As Int = inset - dh + WriteString(ESC & "$" & Chr(dl) & Chr(dh)) + Dim params(2) As Byte + params(0) = dl + params(1) = dh + WriteBytes(params) +End Sub + +' Set the left margin of the print area, must be the first item on a new line +' margin is specified in units of 0.125mm +' This affects barcodes as well as text +Public Sub setLeftMargin(margin As Int) + Dim dh As Int = margin / 256 + Dim dl As Int = margin - dh + WriteString(GS & "L") + Dim params(2) As Byte + params(0) = dl + params(1) = dh + WriteBytes(params) +End Sub + +' Set the width of the print area, must be the first item on a new line +' margin is specified in units of 0.125mm +' This affects barcodes as well as text +' This appears to function more like a right margin than a print area width when used with LeftMargin +Public Sub setPrintWidth(width As Int) + Dim dh As Int = width / 256 + Dim dl As Int = width - dh + WriteString(GS & "W") + Dim params(2) As Byte + params(0) = dl + params(1) = dh + WriteBytes(params) +End Sub + +' Set the distance between lines in increments of 0.125mm +' If spacing is < 0 then the default of 30 is set +Public Sub setLineSpacing(spacing As Int) + If spacing < 0 Then + WriteString(ESC & "2") + Else + WriteString(ESC & "3") + Dim params(1) As Byte + params(0) = spacing + WriteBytes(params) + End If +End Sub + +' Set the line content justification, must be the first item on a new line +' 0 left, 1 centre, 2 right +Public Sub setJustify(justify As Int) + WriteString(ESC & "a" & Chr(justify + 48)) +End Sub + +' Set the codepage of the printer +' You need to look at the printer documentation to establish which codepages are supported +Public Sub setCodePage(codepage As Int) + WriteString(ESC & "t") + Dim params(1) As Byte + params(0) = codepage + WriteBytes(params) +End Sub + +' Select the size of the font for printing text. 0 = Font A (12 x 24), 1 = Font B (9 x 17) +' For font B you may want to set the line spacing to a lower value than the default of 30 +' This affects only the size of printed characters. The code page determines the actual character set +' On my printer setting UseCustomCharacters = while Font B is selected crashes the printer and turns it off +Public Sub setCharacterFont(font As Int) + WriteString(ESC & "M" & Chr(Bit.And(1,font))) +End Sub + +' Set the positions of the horizontal tabs +' Each tab is specified as a number of character widths from the beginning of the line +' There may be up to 32 tab positions specified each of size up to 255 characters +' The printer default is that no tabs are defined +Public Sub setTabPositions(tabs() As Int) + WriteString(ESC & "D") + Dim data(tabs.Length+1) As Byte + For i = 0 To tabs.Length - 1 + data(i) = tabs(i) + Next + data(tabs.Length) = 0 + WriteBytes(data) +End Sub + +' Set print position relative to the current position using horizontal units of 0.125mm +' relposn can be negative +' Unless I have misundertood this doesn't work as documented on my printer +' It only seems take effect at the beginning of a line as a one off effect +Public Sub setRelativePrintPosn(relposn As Int) + Dim dh As Int = relposn / 256 + Dim dl As Int = relposn - dh + WriteString(ESC & "\") + Dim params(2) As Byte + params(0) = dl + params(1) = dh + WriteBytes(params) +End Sub + +' Send the contents of an array of bytes to the printer +' Remember that if the printer is expecting text the bytes will be printed as characters in the current code page +Public Sub WriteBytes(data() As Byte) + If Connected Then + Astream.Write(data) + End If +End Sub + +' Send the string to the printer in IBM437 encoding which is the original PC DOS codepage +' This is usually the default codepage for a printer and is CodePage = 0 +' Beware of using WriteString with Chr() to send numeric values as they may be affected by Unicode to codepage translations +' Most character level operations are pre-defined as UPPERCASE string variables for easy concatenation with other string data +Public Sub WriteString(data As String) + WriteString2(data, "IBM437") +End Sub + +' Send the string to the printer in the specified encoding +' You also need to set the printer to a matching encoding using the CodePage property +' Beware of using WriteString2 with Chr() to send numeric values as they may be affected by codepage substitutions +' Most character level operations are pre-defined as UPPERCASE string variables for easy concatenatipon with other string data +Public Sub WriteString2(data As String, encoding As String) + Try + If Connected Then + Astream.Write(data.GetBytes(encoding)) + End If + Catch + Log("Printer error : " & LastException.Message) + AStream_Error + End Try +End Sub + +'----------------------------------------- +' User defined character commands commands +'----------------------------------------- + +' Delete the specified user defined character mode +' This command deletes the pattern defined for the specified code in the font selected by ESC ! +' If the code is subsequently printed in custom character mode the present code page character is printed instead +Public Sub DeleteCustomCharacter(charcode As Int) + WriteString(ESC & "?") + Dim params(1) As Byte + params(0) = charcode + WriteBytes(params) +End Sub + +' Enable the user defined character mode if custom is True, revert to normal if custom is False +' If a custom character has not been defined for a given character code then the default character for the present font is printed +' FontA and FontB have separate definitions for custom characters +' On my printer setting UseCustomCharacters = while Font B is selected crashes the printer and turns it off +' Therefore the cuatom character routines have not been tested on ont B +Public Sub setUseCustomCharacters(custom As Boolean) + If custom Then + WriteString(ESC & "%1") + Else + WriteString(ESC & "%0") + End If +End Sub + +' Define a user defined character +' The allowable character code range is the 95 characters) from ASCII code 32 (0x20) to 126 (0x7E) +' Characters can be defined in either font A (12*24) or font B (9*17) as selected by present setting of CharacterFont +' The programmer must ensure that the correct font size definition is used for the present setting of CharacterFont +' The user-defined character definition is cleared when Reset is invoked or the printer is turned off +' The vertical and horizontal printed resolution is approximaely 180dpi +' Characters are always defined by sets of three bytes in the vertical direction and up to 9 or 12 sets horizontally +' Each byte defines a vertical line of 8 dots. The MSB of each byte is the highest image pixel, the LSB is the lowest +' Byte(0+n) defines the topmost third of the vertical line, Byte(1+n) is below and Byte(2+n) is the lowest +' Set a bit to 1 to print a dot or 0 to not print a dot +' If the lines to the right of the character are blank then there set of three bytes can be omiited from the byte array +' When the user-defined characters are defined in font B (9*17) only the most significant bit of the 3rd byte of data is used +' charcode defines the character code for the character being defined +' bitdata is a Byte array containing the character definitiopn as described above. +' If the length of bitdata is not a multiple of 3 the definition is ignored and a value of -1 returned +Public Sub DefineCustomCharacter(charcode As Int, bitdata() As Byte) As Int + Dim excess As Int = bitdata.Length Mod 3 + If excess <> 0 Then Return -1 + Dim size As Int = bitdata.Length / 3 + WriteString(ESC & "&") + Dim params(4) As Byte + params(0) = 3 + params(1) = charcode + params(2) = charcode + params(3) = size + WriteBytes(params) + WriteBytes(bitdata) + Return 0 +End Sub + +' The third triangle point is hacked into spare bits keeping the generated Int human readable i hex for other shapes +' The shape array contains the character shapes and characterfont is 0 for a 12*24 character andd 1 for a 9*17 character +' Returns a Byte(36) for characterfont = 0 and a Byte(27) for characterfont = 1 +' The returned array can be directly passed to DefineCustomCharacter +' To define a custom character requires specifying up to 288 data points +' This is a lot of data and in most cases it is mainly white space +' This method takes a character definition that defines only the shapes in the character that are to be printed black +' It will be easier use the outputs from CreateLine, CreateTriangle, CreateBox and CreateCircle rather then building the actual Int values +' Each shape is defined by a single Int value containing four parameters in hex format plugs some single bit flags +' Taking the representation of the Int as eight hex characters numbered from the MS end as 0x01234567 +' 0 contains the shape to draw. 0 = Line, 1 = Box, 2 = Circle, 3 = Triangle +' 1 contains a value between 0 and 0xF. This is either an X coordinate or for a circle the radius +' 2 and 3 contain a value between 0 and 0x1F. This is either a Y coordinate or for a circle the quadrants to draw +' 4 contains a value between 0 and 0xF. This is 0 for an empty shope or 1 for a filled shape +' 5 contains a value between 0 and 0xF. This is an X coordinate +' 5 and 6 contain a value between 0 and 0x1F. This is a Y coordinate +' The coordinate 0,0 is at the top left of the character +' Line +' One point of the vector is contained in the top part of the Int and the other in the bottom half +' To define a single point place its coordinates as both sr=start and end of a line +' Box +' The two X,Y coordinates specify the top left and bottom right corners of the box +' Circle +' The left X parameter is now the radius of the circle, the left Y is the quadrants to be drawn +' The right X and Y parameters are the centre of the circle' +' The quadrants to draw are bit ORed together, UpperRight = 0x1, LowerRight = 0x2, LowerLeft = 0x4, Upper Left = 0x8 +' Triangle +' The left X and Y parameters are now one point of the triangle, the right X and Y parameters another point +' The third triangle point is hacked into spare bits keeping the generated Int human readable in hex for the other shapes +' The bit allocations of a shape are as follows. f = fill as 0 or 1, s = shape as 0 to 7, xn as 0 to 15, yn as 0 to 31 +' Shape 0 = line, 1 = box, 2 = triangle, 3 = circle, 4 to 7 = unused +' fsss xxxx -yyy yyyy xxxx xxxx yyyy yyyy +' 0000 220 0000 2222 1111 2221 1111 +' x0 y2 y0 x2 x1 y2 y1 +' The shape array contains the character shapes and characterfont is 0 for a 12*24 character andd 1 for a 9*17 character +' Returns a Byte(36) for characterfont = 0 and a Byte(27) for characterfont = 1 +' The returned array can be directly passed to DefineCustomCharacter +Public Sub CreateCustomCharacter(shapes() As Int, characterfont As Int) As Byte() + Dim masks(8) As Byte + masks(0) = 0x80 + masks(1) = 0x40 + masks(2) = 0x20 + masks(3) = 0x10 + masks(4) = 0x08 + masks(5) = 0x04 + masks(6) = 0x02 + masks(7) = 0x01 + ' rather than try to catch errors whenever we access this array we Dim it to the maximum possible values of X and Y + ' then copy the top left of it to the final character definition array of the correct size + Dim points(16,32) As Byte + ' initialise the character to all white + For x = 0 To 15 + For y = 0 To 31 + points(x,y) = 0 + Next + Next + Dim size As Int = 12 + If characterfont = 1 Then size = 9 + Dim charbyes(size * 3) As Byte + For c = 0 To charbyes.Length - 1 + charbyes(c) = 0 + Next + ' set the points array from the shapes provided + For i = 0 To shapes.Length -1 + Dim fill As Int = Bit.UnsignedShiftRight(Bit.And(0x80000000, shapes(i)), 31) + Dim shape As Int = Bit.UnsignedShiftRight(Bit.And(0x70000000, shapes(i)), 28) + Dim x0 As Int = Bit.UnsignedShiftRight(Bit.And(0x0f000000, shapes(i)), 24) + Dim y0 As Int = Bit.UnsignedShiftRight(Bit.And(0x001f0000, shapes(i)), 16) + Dim x1 As Int = Bit.UnsignedShiftRight(Bit.And(0x00000f00, shapes(i)), 8) + Dim y1 As Int = Bit.And(0x0000001f, shapes(i)) + Dim x2 As Int = Bit.UnsignedShiftRight(Bit.And(0x0000f000, shapes(i)), 12) + Dim y2 As Int = Bit.UnsignedShiftRight(Bit.And(0x00e00000, shapes(i)), 18) + Bit.UnsignedShiftRight(Bit.And(0x000000e0, shapes(i)), 5) + ' The bit allocations of a shape are as follows. f = fill as 0 or 1, s = shape as 0 to 7, xn as 0 to 15, yn as 0 to 31 + ' Shape 0 = line, 1 = box, 2 = triangle, 3 = circle, 4 to 7 = unused + ' fsss xxxx -yyy yyyy xxxx xxxx yyyy yyyy + ' 0000 220 0000 2222 1111 2221 1111 + ' x0 y2 y0 x2 x1 y2 y1 + Dim logmsg As String = ": Fill=" & fill & " : Points " & x0 & "," & y0 & " " & x1 & "," & y1 & " " & x2 & "," & y2 + If shape = 3 Then + Log("Triangle " & logmsg) + PlotTriangle(x0, y0, x1, y1, x2, y2, points, fill) + else If shape = 2 Then + Log("Circle " & logmsg) + PlotCircle(x0, y0, x1, y1, points, fill) + Else If shape = 1 Then + Log("Box " & logmsg) + PlotBox(x0, y0, x1, y1, points, fill) + Else + Log("Line " & logmsg) + PlotLine(x0, y0, x1, y1, points) + End If + ' map the points array onto the character definition array + For x = 0 To size -1 ' 9 or 12 horizontal bytes + For y = 0 To 2 ' 3 vertical bytes + Dim bits As Byte = 0 + For b = 0 To 7 ' 8 vertical bits + If points(x, y*8+b) <> 0 Then + bits = Bit.Or(bits, masks(b)) + End If + Next + charbyes(x*3+y) = bits + Next + Next + Next + Return charbyes +End Sub + +' This is a higher level method that builds the Int values to pass to CreateCustomCharacter in the shapes array +' Create the value to draw a line in a custom character +' The line starts at X0,Y0 and ends at X1,Y1 +Public Sub CreateLine(x0 As Int, y0 As Int, x1 As Int, y1 As Int) As Int + Dim line As Int = 0 + line = line + Bit.ShiftLeft(Bit.And(0xf,x0), 24) + line = line + Bit.ShiftLeft(Bit.And(0x1f,y0), 16) + line = line + Bit.ShiftLeft(Bit.And(0xf,x1), 8) + line = line + Bit.And(0x1f,y1) + Return line +End Sub + +' This is a higher level method that builds the Int values to pass to CreateCustomCharacter in the shapes array +' Create the value to draw a circle in a custom character +' The circle is centred on X1,Y1 and the quadrants to draw are bit ORed together +' UpperRight = 0x1, LowerRight = 0x2, LowerLeft = 0x4, Upper Left = 0x8 +Public Sub CreateCircle(radius As Int, quadrants As Int, x1 As Int, y1 As Int, fill As Boolean) As Int + Dim circle As Int = 0x20000000 + If fill Then circle = circle + 0x80000000 + circle = circle + Bit.ShiftLeft(radius, 24) + circle = circle + Bit.ShiftLeft(quadrants, 16) + circle = circle + Bit.ShiftLeft(x1, 8) + circle = circle + y1 + Return circle +End Sub + + +' This is a higher level method that builds the Int values to pass to CreateCustomCharacter in the shapes array +' Create the value to draw a triangle in a custom character +' The triangles corners are at X0,Y0 X1,Y1 and X2,Y2 +Public Sub CreateTriangle(x0 As Int, y0 As Int, x1 As Int, y1 As Int, x2 As Int, y2 As Int, fill As Boolean) As Int + Dim triangle As Int = 0x30000000 + If fill Then triangle = triangle + 0x80000000 + triangle = triangle + Bit.ShiftLeft(Bit.And(0xf,x0), 24) + triangle = triangle + Bit.ShiftLeft(Bit.And(0x1f,y0), 16) + triangle = triangle + Bit.ShiftLeft(Bit.And(0xf,x1), 8) + triangle = triangle + Bit.And(0x1f,y1) + triangle = triangle + Bit.ShiftLeft(Bit.And(0xf,x2), 12) ' extra X + triangle = triangle + Bit.ShiftLeft(Bit.And(0x7,y2), 5) ' extra Y lsbits * 3 + triangle = triangle + Bit.ShiftLeft(Bit.And(0x18,y2), 18) ' extra Y msbits * 2 + Return triangle +End Sub + +' This is a higher level method that builds the Int values to pass to CreateCustomCharacter in the shapes array +' Create the value to draw a box in a custom character +' The box top left start is X0,Y0 and bottom right is X1,Y1 +Public Sub CreateBox(x0 As Int, y0 As Int, x1 As Int, y1 As Int, fill As Boolean) As Int + Dim box As Int = 0x10000000 + If fill Then box = box + 0x80000000 + box = box + Bit.ShiftLeft(Bit.And(0xf,x0), 24) + box = box + Bit.ShiftLeft(Bit.And(0x1f,y0), 16) + box = box + Bit.ShiftLeft(Bit.And(0xf,x1), 8) + box = box + Bit.And(0x1f,y1) + Return box +End Sub + +'----------------------------------------- +' Private custom character drawing methods +'----------------------------------------- + +Private Sub PlotTriangle(x0 As Int, y0 As Int, x1 As Int, y1 As Int, x2 As Int, y2 As Int, points(,) As Byte, Fill As Int) + ' This is a pretty crude algorithm, but it is simple, works and it isn't invoked often + PlotLine(x0, y0, x1, y1, points) + PlotLine(x1, y1, x2, y2, points) + PlotLine(x2, y2, x0, y0, points) + If Fill > 0 Then + FillTriangle(x0, y0, x1, y1, x2, y2, points) + End If +End Sub + +Private Sub FillTriangle(x0 As Int, y0 As Int, x1 As Int, y1 As Int, x2 As Int, y2 As Int, points(,) As Byte) + ' first sort the three vertices by y-coordinate ascending so v0 Is the topmost vertice */ + Dim tx, ty As Int + If y0 > y1 Then + tx = x0 : ty = y0 + x0 = x1 : y0 = y1 + x1 = tx : y1 = ty + End If + If y0 > y2 Then + tx = x0 : ty = y0 + x0 = x2 : y0 = y2 + x2 = tx : y2 = ty + End If + If y1 > y2 Then + tx = x1 : ty = y1 + x1 = x2 : y1 = y2 + x2 = tx : y2 = ty + End If + + Dim dx0, dx1, dx2 As Double + Dim x3, x4, y3, y4 As Double + Dim inc As Int + + If y1 - y0 > 0 Then dx0=(x1-x0)/(y1-y0) Else dx0=0 + If y2 - y0 > 0 Then dx1=(x2-x0)/(y2-y0) Else dx1=0 + If y2 - y1 > 0 Then dx2=(x2-x1)/(y2-y1) Else dx2=0 + x3 = x0 : x4 = x0 + y3 = y0 : y4 = y0 + If dx0 > dx1 Then + While + Do While y3 <= y1 + If x3 > x4 Then inc = -1 Else inc = 1 + For x = x3 To x4 Step inc + points(x, y3) = 1 + Next + y3 = y3 + 1 : y4 = y4 + 1 : x3 = x3 + dx1 : x4 = x4 + dx0 + Loop + x4=x1 + y4=y1 + Do While y3 <= y2 + If x3 > x4 Then inc = -1 Else inc = 1 + For x = x3 To x4 Step inc + points(x ,y3) = 1 + Next + y3 = y3 + 1 : y4 = y4 + 1 : x3 = x3 + dx1 : x4 = x4 + dx2 + Loop + Else + While + Do While y3 <= y1 + If x3 > x4 Then inc = -1 Else inc = 1 + For x = x3 To x4 Step inc + points(x, y3) = 1 + Next + y3 = y3 + 1 : y4 = y4 + 1 : x3 = x3 + dx0 : x4 = x4 +dx1 + Loop + x3=x1 + y3=y1 + Do While y3<=y2 + If x3 > x4 Then inc = -1 Else inc = 1 + For x = x3 To x4 Step inc + points(x, y3) = 1 + Next + y3 = y3 + 1 : y4 = y4 + 1 : x3 = x3 + dx2 : x4 = x4 + dx1 + Loop + End If +End Sub + +Private Sub PlotBox(x0 As Int, y0 As Int, x1 As Int, y1 As Int, points(,) As Byte, Fill As Int) + ' This is a pretty crude algorithm, but it is simple, works and itsn't invoked often + PlotLine(x0, y0, x0, y1, points) + PlotLine(x0, y0, x1, y0, points) + PlotLine(x1, y0, x1, y1, points) + PlotLine(x0, y1, x1, y1, points) + If Fill > 0 Then + For x = x0 To x1 + PlotLine(x, y0, x, y1, points) + Next + End If +End Sub + + +Private Sub PlotCircle(radius As Int, quadrants As Int, x1 As Int, y1 As Int, points(,) As Byte, fill As Int) + ' This is a pretty crude algorithm, but it is simple, works and itsn't invoked often + Dim mask As Int = 1 + For q = 3 To 0 Step -1 + If Bit.And(quadrants, mask) <> 0 Then + For i = q*90 To q*90+90 Step 1 + Dim x,y As Double + x = x1 - SinD(i)*radius + y = y1 - CosD(i)*radius + If fill > 0 Then + PlotLine(x1, y1, x, y, points) + Else + points(Round(x), Round(y)) = 1 + End If + Next + End If + mask = Bit.ShiftLeft(mask, 1) + Next +End Sub + +' Bresenham's line algorithm - see Wikipedia +Private Sub PlotLine(x0 As Int, y0 As Int, x1 As Int, y1 As Int, points(,) As Byte ) + If Abs(y1 - y0) < Abs(x1 - x0) Then + If x0 > x1 Then + PlotLineLow(x1, y1, x0, y0, points) + Else + PlotLineLow(x0, y0, x1, y1, points) + End If + Else + If y0 > y1 Then + PlotLineHigh(x1, y1, x0, y0, points) + Else + PlotLineHigh(x0, y0, x1, y1, points) + End If + End If +End Sub + +Private Sub PlotLineHigh(x0 As Int, y0 As Int, x1 As Int, y1 As Int, points(,) As Byte ) + Dim dx As Int = x1 - x0 + Dim dy As Int = y1 - y0 + Dim xi As Int = 1 + If dx < 0 Then + xi = -1 + dx = -dx + End If + Dim D As Int = 2*dx - dy + Dim x As Int = x0 + For y = y0 To y1 + points(x,y) = 1 + If D > 0 Then + x = x + xi + D = D - 2*dy + End If + D = D + 2*dx + Next +End Sub + +Private Sub PlotLineLow(x0 As Int, y0 As Int, x1 As Int,y1 As Int, points(,) As Byte ) + Dim dx As Int = x1 - x0 + Dim dy As Int = y1 - y0 + Dim yi As Int = 1 + If dy < 0 Then + yi = -1 + dy = -dy + End If + Dim D As Int = 2*dy - dx + Dim y As Int = y0 + For x = x0 To x1 + points(x,y) = 1 + If D > 0 Then + y = y + yi + D = D - 2*dx + End If + D = D + 2*dy + Next +End Sub + + +'------------------- +' Image commands +'------------------- +' There are two different image printing options with different pixel formats. +' PrintImage prints an entire image at once with a maximum size of 576x512 +' PrintImage2 prints a slice of an image with a height of 8 or 24 and a maximum width of 576 +' One or other may look better on your particular printer + +' Printer support method for pre-processing images to print +' Convert the bitmap supplied to an array of pixel values representing the luminance value of each original pixel +Sub ImageToBWIMage(bmp As Bitmap) As AnImage + Dim BC As BitmapCreator 'ignore + Dim W As Int = bmp.Width + Dim H As Int = bmp.Height + Dim pixels(W * H) As Byte + + For y = 0 To H - 1 + For x = 0 To W - 1 + Dim j As Int = bmp.GetPixel(x, y) + ' convert color to approximate luminance value + Dim col As ARGBColor + BC.ColorToARGB(j, col ) + Dim lum As Int = col.r * 0.2 + col.b*0.1 + col.g*0.7 + If lum> 255 Then lum = 255 + ' save the pixel luminance + pixels(y*W + x) = lum + Next + Next + Dim ret As AnImage + ret.Width = bmp.Width + ret.Height = bmp.Height + ret.Data = pixels + Return ret +End Sub + +' Printer support method for pre-processing images to print +' Convert the array of luminance values to an array of 0s and 1s according to the threshold value +Sub ThresholdImage(img As AnImage, threshold As Int) As AnImage 'ignore + Dim pixels(img.Data.Length) As Byte + For i = 0 To pixels.Length - 1 + Dim lum As Int = Bit.And(img.Data(i), 0xff) ' bytes are signed values + If lum < threshold Then + lum = 1 + Else + lum = 0 + End If + pixels(i) = lum + Next + Dim ret As AnImage + ret.Width = img.Width + ret.Height = img.Height + ret.Data = pixels + Return ret +End Sub + +' Printer support method for pre-processing images to print +' Convert the array of luminance values to a dithered array of 0s and 1s according to the threshold value +' The dithering algorithm is the simplest one-dimensional error diffusion algorithm +' Normally threshold should be 128 but some images may look better with a little more or less. +' This algorithm tends to produce vertical lines. DitherImage2D will probably look far better +Sub DitherImage1D(img As AnImage, threshold As Int) As AnImage 'ignore + Dim pixels(img.Data.Length) As Byte + Dim error As Int + For y = 0 To img.Height - 1 + error = 0 ' reset on each new line + For x = 0 To img.Width - 1 + Dim lum As Int = Bit.And(img.Data(y*img.Width + x), 0xff) ' bytes are signed values + lum = lum + error + If lum < threshold Then + error = lum + lum = 1 + Else + error = lum - 255 + lum = 0 + End If + pixels(y*img.Width + x) = lum + Next + Next + Dim ret As AnImage + ret.Width = img.Width + ret.Height = img.Height + ret.Data = pixels + Return ret +End Sub + + +' Printer support method for pre-processing images to print +' Convert the array of luminance values to a dithered array of 0s and 1s according to the threshold value +' The dithering algorithm is the simplest two-dimensional error diffusion algorithm +' Normally threshold should be 128 but some images may look better with a little more or less. +' Anything more sophisticated might be overkill considering the image quality of most thermal printers +Sub DitherImage2D(img As AnImage, threshold As Int) As AnImage + Dim pixels(img.Data.Length) As Byte + Dim xerror As Int + Dim yerrors(img.Width) As Int + For i = 0 To yerrors.Length -1 + yerrors(0) = 0 + Next + For y = 0 To img.Height - 1 + xerror = 0 ' reset on each new line + For x = 0 To img.Width - 1 + Dim lum As Int = Bit.And(img.Data(y*img.Width + x), 0xff) ' bytes are signed values + lum = lum + xerror + yerrors(x) + If lum < threshold Then + xerror = lum/2 + yerrors(x) = xerror + lum = 1 + Else + xerror = (lum - 255)/2 + yerrors(x) = xerror + lum = 0 + End If + pixels(y*img.Width + x) = lum + Next + Next + Dim ret As AnImage + ret.Width = img.Width + ret.Height = img.Height + ret.Data = pixels + Return ret +End Sub + + +' GS v0 printing +'--------------- + +' Prints the given image at the specified height and width using the "GS v" command +' Image data is supplied as bytes each containing 8 bits of horizontal image data +' The top left of the image is Byte(0) and the bottom right is Byte(width*height-1) +' MSB of the byte is the leftmost image pixel, the LSB is the rightmost +' Maximum width is 72 bytes (576 bits), Maximum height is 512 bytes +' The printed pixels are square +' Returns status 0 : OK, -1 : too wide, -2 : too high, -3 : array too small +' The printer can take a long time to process the data and start printing +Public Sub PrintImage(img As AnImage) As Int + ' max width = 72 ' 72mm/576 bits wide + ' max height = 512 ' 64mm/512 bits high + If img.width > 72 Then Return -1 + If img.height > 512 Then Return -2 + If img.data.Length < img.width * img.height Then Return -3 + Dim xh As Int = img.width / 256 + Dim xl As Int = img.width - xh * 256 + Dim yh As Int = img.height / 256 + Dim yl As Int = img.height - yh * 256 + Dim params(5) As Byte + params(0) = 0 ' + params(1) = xl + params(2) = xh + params(3) = yl + params(4) = yh + WriteString(GS & "v0") + WriteBytes(params) + WriteBytes(img.data) + WriteString(CRLF) + Return 0 +End Sub + +' Printer support method for pre-processing images to print by PrintImage +' Takes an array of image pixels and packs it for use with PrintImage +' Each byte in the imagedata array is a single pixel valued zero or non-zero for white and black +' The returned array is 8 x smaller and packs 8 horizontal black or white pixels into each byte +' If the horizontal size of the image is not a multiple of 8 it will be truncated so that it is. +Public Sub PackImage(imagedata As AnImage) As AnImage + Dim xbytes As Int = imagedata.width/8 + Dim pixels(xbytes * imagedata.height) As Byte + Dim masks(8) As Byte + masks(0) = 0x80 + masks(1) = 0x40 + masks(2) = 0x20 + masks(3) = 0x10 + masks(4) = 0x08 + masks(5) = 0x04 + masks(6) = 0x02 + masks(7) = 0x01 + Dim index As Int = 0 + For y = 0 To imagedata.Height - 1 + For x = 0 To xbytes - 1 + Dim xbyte As Byte = 0 + For b = 0 To 7 + ' get a pixel + Dim pix As Byte = imagedata.Data(index) + If pix <> 0 Then + xbyte = xbyte + masks(b) + End If + index = index + 1 + Next + pixels(y*xbytes + x) = xbyte + Next + Next + Dim ret As AnImage + ret.Width = xbytes + ret.Height = imagedata.Height + ret.Data = pixels + Return ret +End Sub + + +' ESC * printing +'--------------- + +' Prints the given image slice at the specified height and width using the "ESC *" command +' Image data is supplied as bytes each containing 8 bits of vertical image data +' Pixels are not square, the width:height ratio varies with density and line height +' Returns status 0 = OK, -1 = too wide, -2 = too high, -3 = wrong array length +' Line spacing needs to be set to 0 if printing consecutive slices +' The printed pixels are not square, the ratio varies with the highdensity and dots24 parameter settings +' The highdensity parameter chooses high or low horizontal bit density when printed +' The dots24 parameter chooses 8 or 24 bit data slice height when printed +' Not(highdensity) +' Maximum width is 288 bits. Horizontal dpi is approximately 90 +' MSB of each byte is the highest image pixel, the LSB is the lowest +' highdensity +' Maximum width is 576 bits. Horizontal dpi is approximately 180 +' Not(dots24) +' Vertical printed height is 8 bits at approximately 60dpi +' One byte in the data Array represents one vertical line when printed +' Array size is the same as the width +' MSB of each byte is the highest image pixel, the LSB is the lowest +' dots24 +' Vertical printed height is 24 bits at approximately 180dpi +' Three consecutive bytes in the data array represent one vertical 24bit line when printed +' Array size is 3 times the width +' Byte(n+0) is the highest, byte (n+2) us the lowest +' MSB of each byte is the highest image pixel, the LSB is the lowest +Public Sub PrintImage2(width As Int, data() As Byte, highdensity As Boolean, dotds24 As Boolean) As Int + Dim d As String = Chr(0) + If Not(highdensity) And Not(dotds24 ) Then + d = Chr(0) + If width > 288 Then Return -1 + If data.Length <> width Then Return -3 + Else If highdensity And Not(dotds24) Then + d = Chr(1) + If width > 576 Then Return -1 + If data.Length <> width Then Return -3 + Else If Not(highdensity) And dotds24 Then + d = Chr(32) + If width > 288 Then Return -1 + If data.Length <> width*3 Then Return -3 + Else ' highdensity And dotds24 + d = Chr(33) + If width > 576 Then Return -1 + If data.Length <> width*3 Then Return -3 + End If + Dim xh As Int = width / 256 + Dim xl As Int = width - xh * 256 + Dim params(2) As Byte + params(0) = xl + params(1) = xh + WriteString(ESC & "*" & d) + WriteBytes(params) + WriteBytes(data) + WriteString(CRLF) + Return 0 +End Sub + +' Printer support method for pre-processing images to print by PrintImage2 +' Takes an array of image pixels and packs one slice of it for use with PrintImage2 +' Each byte in the imagedata array is a single pixel valued zero or non-zero for white and black +' The returned array packs 8 vertical black or white pixels into each byte +' If dots24 is True then the slice is 24 pixels high otherwise it is 8 pixels high +Public Sub PackImageSlice(img As AnImage, slice As Int, dots24 As Boolean) As Byte() + Dim bytes As Int = img.width + If dots24 Then + Dim pixels(bytes * 3) As Byte + Dim slicestart As Int = slice * bytes * 8 * 3 + Else + Dim pixels(bytes) As Byte + Dim slicestart As Int = slice * bytes * 8 + End If + + Dim masks(8) As Byte + masks(0) = 0x80 + masks(1) = 0x40 + masks(2) = 0x20 + masks(3) = 0x10 + masks(4) = 0x08 + masks(5) = 0x04 + masks(6) = 0x02 + masks(7) = 0x01 + ' You could compress this into a single code block but I left it as two to make it more obvious what's happening + If dots24 Then + For x = 0 To bytes - 1 + For s = 0 To 2 + Dim xbyte As Byte = 0 + For b = 0 To 7 + ' get a pixel + Dim pix As Byte = img.Data(slicestart + ((b + s*8) * bytes) + x) + If pix <> 0 Then + xbyte = xbyte + masks(b) + End If + Next + pixels(x*3+s) = xbyte + Next + Next + Else + For x = 0 To bytes - 1 + Dim xbyte As Byte = 0 + For b = 0 To 7 + ' get a pixel + Dim pix As Byte = img.Data(slicestart + (b * bytes) + x) + If pix <> 0 Then + xbyte = xbyte + masks(b) + End If + Next + pixels(x) = xbyte + Next + End If + Return pixels +End Sub + +'---------------- +'Barcode commands +'---------------- + +' Set the height of a 2D bar code as number of dots vertically, 1 to 255 +' Automatically resets to the default after printing the barcode +Public Sub setBarCodeHeight(height As Int) + WriteString(GS & "h") + Dim params(1) As Byte + params(0) = height + WriteBytes(params) +End Sub + +' Set the left inset of a 2D barcode, 0 to 255 +' This does not reset on receipt of RESET +Public Sub setBarCodeLeft(left As Int) + WriteString(GS & "x") + Dim params(1) As Byte + params(0) = left + WriteBytes(params) +End Sub + +' Set the width of each bar in a 2D barcode. width value is 2 to 6, default is 3 +' 2 = 0.250, 3 - 0.375, 4 = 0.560, 5 = 0.625, 6 = 0.75 +' Resets to default after printing the barcode +Public Sub setBarCodeWidth(width As Int) + WriteString(GS & "w") + Dim params(1) As Byte + params(0) = width + WriteBytes(params) +End Sub + +'Selects the printing position of HRI (Human Readable Interpretation) characters when printing a 2D bar code. +'0 Not printed, 1 Above the bar code, 2 Below the bar code, 3 Both above And below the bar code +' Automatically resets to the default of 0 after printing the barcode +' The docs say this can be Chr(0, 1 2 or 3) or "0" "1" "2" or "3" but the numeric characters don't work +Public Sub setHriPosn(posn As Int) + WriteString(GS & "H") + Dim params(1) As Byte + params(0) = posn + WriteBytes(params) +End Sub + +'Selects the font for HRI (Human Readable Interpretation) characters when printing a 2D bar code. +'0 Font A (12 x 24), 1 Font B (9 x 17) +' Automatically resets to the default of 0 after printing the barcode +' The docs say this can be Chr(0 or 1) or "0" or "1" but the numeric characters don't work +Public Sub setHriFont(font As Int) + WriteString(GS & "f" & Chr(font)) +End Sub + +' If given invalid data no barcode is printed, only strange characters +' CODABAR needs any of A,B,C or D at the start and end of the barcode. Some decoders may not like them anywhere else +' Bartype Code Number of characters Permitted values +' A | UPC-A | 11 or 12 characters | 0 to 9 | The 12th printed character is always the check digit +' B | UPC-E | 6 characters | 0 to 9 | The 12th printed character is always the check digit +' C | EAN13 | 12 or 13 characters | 0 to 9 | The 12th printed character is always the check digit +' D | EAN8 | 7 or 8 characters | 0 to 9 | The 8th printed character is always the check digit +' E | CODE39 | 1 or more characters | 0 to 9, A to Z, Space $ % + - . / +' F | ITF | 1 or more characters | 0 to 9 | even number of characters only +' G | CODABAR| 3 to 255 characters | 0 to 9, A to D, $ + - . / : | needs any of A,B,C or D at the start and end +' H | CODE93 | 1 to 255 characters | Same as CODE39 +' I | CODE128| 2 to 255 characters | entire 7 bit ASCII set +Public Sub WriteBarCode(bartype As String, data As String) + Dim databytes() As Byte = data.GetBytes("ASCII") + Dim dlow As Int = databytes.Length + Log("Barcode " & bartype & ", Size " & dlow & ", " & data) + WriteString(GS & "k" & bartype.ToUpperCase.CharAt(0)) + Dim params(1) As Byte + params(0) = dlow + WriteBytes(params) + WriteBytes(databytes) +End Sub + +' On my printer QR codes don't seem to be able to be decoded and on high ECs look obviously wrong :( +' size is 1 to 40, 0 is auto-size. Successive versions increase module size by 4 each side +' size = 1 is 21x21, 2 = 25x25 ... size 40 = 177x177 +' EC is error correction level, "L"(7%) or "M"(15%) or "Q"(25%) or "H"(30%) +' scale is 1 to 8, 1 is smallest, 8 is largest +Public Sub WriteQRCode(size As Int, EC As String, scale As Int, data As String) + Dim databytes() As Byte = data.GetBytes("ISO-8859-1") + Dim dhigh As Int = databytes.Length / 256 + Dim dlow As Int = databytes.Length - dhigh*256 + Log("QR Code : Size " & size & ", EC " & EC & ", Scale " & scale & ", Size " & dlow & " " & dhigh & " : Data = " & data) + Dim params(3) As Byte + params(0) = scale + params(1) = dlow + params(2) = dhigh + WriteString(ESC & "Z" & Chr(size) & EC.ToUpperCase.CharAt(0)) + WriteBytes(params) + WriteBytes(databytes) +End Sub + + +'**************** +' PRIVATE METHODS +'**************** + +'----------------------- +' Internal Serial Events +'----------------------- + +Private Sub Serial1_Connected (Success As Boolean) + If Success Then + Astream.Initialize(Serial1.InputStream, Serial1.OutputStream, "astream") + Connected = True + ConnectedError = "" + Serial1.Listen + Else + Connected = False + ConnectedError = LastException.Message + End If + If SubExists(CallBack, EventName & "_Connected") Then + CallSub2(CallBack, EventName & "_Connected", Success) + End If +End Sub + +'---------------------------- +' Internal AsyncStream Events +'---------------------------- + +Private Sub AStream_NewData (Buffer() As Byte) + If SubExists(CallBack, EventName & "_NewData") Then + CallSub2(CallBack, EventName & "_NewData", Buffer) + End If + Log("Data " & Buffer(0)) +End Sub + +Private Sub AStream_Error + If SubExists(CallBack, EventName & "_Error") Then + CallSub(CallBack, EventName & "_Error") + End If +End Sub + +Private Sub AStream_Terminated + Connected = False + If SubExists(CallBack, EventName & "_Terminated") Then + CallSub(CallBack, EventName & "_Terminated") + End If +End Sub diff --git a/B4A/Estacionamiento.b4a b/B4A/Estacionamiento.b4a new file mode 100644 index 0000000..39f93ae --- /dev/null +++ b/B4A/Estacionamiento.b4a @@ -0,0 +1,105 @@ +Build1=Default,Estacionamiento.Keymon.Lat +File1=alert2.png +File2=LogoEstacionamiento.png +File3=MainPage.bal +FileGroup1=Default Group +FileGroup2=Default Group +FileGroup3=Default Group +Group=Default Group +Library1=b4xpages +Library10=gps +Library11=httputils2 +Library12=json +Library13=phone +Library14=randomaccessfile +Library15=serial +Library16=sql +Library17=stringutils +Library2=bitmapcreator +Library3=ble2 +Library4=byteconverter +Library5=compressstrings +Library6=core +Library7=fileprovider +Library8=firebasenotifications +Library9=fusedlocationprovider +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~AddManifestText(~\n~~\n~)~\n~AddPermission(android.permission.ACCESS_BACKGROUND_LOCATION)~\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~ ~\n~SetApplicationAttribute(android:largeHeap, "true")~\n~~\n~AddManifestText(~\n~ )~\n~AddApplicationText(~\n~ ~\n~ ~\n~ ~\n~)~\n~CreateResource(xml, provider_paths,~\n~~\n~ ~\n~ ~\n~ ~\n~~\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.MANAGE_EXTERNAL_STORAGE")~\n~AddPermission(android.permission.READ_PHONE_STATE)~\n~AddPermission(android.permission.WAKE_LOCK)~\n~SetApplicationAttribute(android:allowBackup, "false")~\n~AddManifestText()~\n~AddApplicationText(~\n~~\n~ ~\n~ )~\n~AddPermission(android.permission.BLUETOOTH_ADVERTISE)~\n~AddPermission(android.permission.BLUETOOTH_CONNECT)~\n~AddPermission(android.permission.BLUETOOTH_SCAN)~\n~AddManifestText() +Module1=|relative|..\B4XMainPage +Module2=C_Principal +Module3=DBRequestManager +Module4=EscPosPrinter +Module5=Starter +Module6=Subs +NumberOfFiles=3 +NumberOfLibraries=17 +NumberOfModules=6 +Version=12.8 +@EndOfDesignText@ +#Region Project Attributes + #ApplicationLabel: Estacionamiento + #VersionCode: 1 + #VersionName: 1.01.01 + 'SupportedOrientations possible values: unspecified, landscape or portrait. + #SupportedOrientations: portrait + #CanInstallToExternalStorage: False +#End Region + +#Region Activity Attributes + #FullScreen: True + #IncludeTitle: False +#End Region + +'#BridgeLogger: True + +Sub Process_Globals + Public ActionBarHomeClicked As Boolean +End Sub + +Sub Globals + +End Sub + +Sub Activity_Create(FirstTime As Boolean) + Dim pm As B4XPagesManager + pm.Initialize(Activity) +End Sub + +'Template version: B4A-1.01 +#Region Delegates + +Sub Activity_ActionBarHomeClick + ActionBarHomeClicked = True + B4XPages.Delegate.Activity_ActionBarHomeClick + ActionBarHomeClicked = False +End Sub + +Sub Activity_KeyPress (KeyCode As Int) As Boolean + Return B4XPages.Delegate.Activity_KeyPress(KeyCode) +End Sub + +Sub Activity_Resume + B4XPages.Delegate.Activity_Resume +End Sub + +Sub Activity_Pause (UserClosed As Boolean) + B4XPages.Delegate.Activity_Pause +End Sub + +Sub Activity_PermissionResult (Permission As String, Result As Boolean) + B4XPages.Delegate.Activity_PermissionResult(Permission, Result) +End Sub + +Sub Create_Menu (Menu As Object) + B4XPages.Delegate.Create_Menu(Menu) +End Sub + +#if Java +public boolean _onCreateOptionsMenu(android.view.Menu menu) { + processBA.raiseEvent(null, "create_menu", menu); + return true; + +} +#End If +#End Region + +'Program code should go into B4XMainPage and other pages. \ No newline at end of file diff --git a/B4A/Estacionamiento.b4a.meta b/B4A/Estacionamiento.b4a.meta new file mode 100644 index 0000000..16db155 --- /dev/null +++ b/B4A/Estacionamiento.b4a.meta @@ -0,0 +1,24 @@ +ModuleBookmarks0= +ModuleBookmarks1= +ModuleBookmarks2= +ModuleBookmarks3= +ModuleBookmarks4= +ModuleBookmarks5= +ModuleBookmarks6= +ModuleBreakpoints0= +ModuleBreakpoints1= +ModuleBreakpoints2= +ModuleBreakpoints3= +ModuleBreakpoints4= +ModuleBreakpoints5= +ModuleBreakpoints6= +ModuleClosedNodes0=6 +ModuleClosedNodes1= +ModuleClosedNodes2= +ModuleClosedNodes3= +ModuleClosedNodes4= +ModuleClosedNodes5= +ModuleClosedNodes6= +NavigationStack=B4XMainPage,AjustarInterfaz,111,6,B4XMainPage,b_rescan_Click,654,2,B4XMainPage,b_tar_in_Click,619,6,B4XMainPage,b_resacep_Click,668,0,B4XMainPage,b_resdia_Click,661,6,B4XMainPage,b_salida_LongClick,188,0,Diseñador Visual,MainPage.bal,-100,6,B4XMainPage,b_entrada_Click,145,2,B4XMainPage,b_salida_Click,163,6,B4XMainPage,b_Tarifa_Click,607,4,B4XMainPage,b_tar_can_Click,614,1 +SelectedBuild=0 +VisibleModules=1,3,6,2,5,4 diff --git a/B4A/Files/alert2.png b/B4A/Files/alert2.png new file mode 100644 index 0000000..44d3b7e Binary files /dev/null and b/B4A/Files/alert2.png differ diff --git a/B4A/Files/logoestacionamiento.png b/B4A/Files/logoestacionamiento.png new file mode 100644 index 0000000..145014b Binary files /dev/null and b/B4A/Files/logoestacionamiento.png differ diff --git a/B4A/Files/mainpage.bal b/B4A/Files/mainpage.bal new file mode 100644 index 0000000..53f690d Binary files /dev/null and b/B4A/Files/mainpage.bal differ diff --git a/B4A/FirebaseMessaging.bas b/B4A/FirebaseMessaging.bas new file mode 100644 index 0000000..c3fe1e1 --- /dev/null +++ b/B4A/FirebaseMessaging.bas @@ -0,0 +1,226 @@ +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" 'Api_Key cheveguerra@gmail.com/Pusher + Dim locRequest As String +' Dim phn As Phone + Dim pe As PhoneEvents + Dim c As Cursor + Public GZip As GZipStrings + Dim Sprvsr As String = "Sprv-Cedex" ' El topico al que se mandan los mensajes push + Dim Subscrito As String + Dim au As String 'ignore +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") 'Topico general Keymon + fm.SubscribeToTopic("Trckr") 'Tracker Global +' Log("Suscrito al tracker global") + fm.SubscribeToTopic("Trckr-Cedex") 'Topico de Guna + If "Cdx_"&B4XPages.MainPage.usuario <> Subscrito Then + fm.SubscribeToTopic("Cdx_"&B4XPages.MainPage.usuario) 'Propio (you can subscribe to more topics) + fm.UnsubscribeFromTopic(Subscrito) 'Unsubscribe from topic + End If +' Log("Subscrito a "&"Cdx_"&B4XPages.MainPage.usuario) + Subscrito = "Cdx_"&B4XPages.MainPage.usuario +' Log(fm.token) +' fm.UnsubscribeFromTopic("Sprvsr") 'Unsubscribe from topic +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 + 15 * DateTime.TicksPerMinute, True) 'Iniciamos servicio cada XX minutos +End Sub + +Sub fm_MessageArrived (Message As RemoteMessage) + Log("Message arrived") + 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 + Log("Es una peticion de ubicacion") + locRequest="Activa" + Log("Llamamos StartFLPSmall") + CallSubDelayed(Tracker, "StartFLPSmall") + 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 + Log("Es un ping") + Log("Mandamos pong") + Dim params As Map = CreateMap("topic":Sprvsr,"title":"pong", "body":B4XPages.MainPage.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 + Log("Es una instruccion de borrar archivo gps") + Log("Borramos archivo gps") + borramosArchivoGPS + End If + If tipos.IndexOf("dr") <> -1 Then 'Si es una peticion de ruta gps + Log("Es una peticion de Ruta GPS") + Dim rutaGpsCmp As String = dameRuta + Dim params As Map = CreateMap("topic":Sprvsr,"title":"ruta", "body":B4XPages.MainPage.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 + Log("Es una instruccion de borrar BD gps") + 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 + Log("No es ping ni solicitud de ubicacion o ruta, entonces no hacemos nada") + End If + End If +' Dim n As Notification +' n.Initialize +' n.Icon = "icon" +' n.SetInfo("Guna", "Guna", Main) +' n.Notify(1) +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 + Log("Con ruta") + Dim rutaGpsCmp As String= params.Get("r") + Else + 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":B4XPages.MainPage.usuario, "t":tipo, "b":B4XPages.MainPage.batt, "mt":B4XPages.MainPage.montoActual, "r":rutaGpsCmp, "v":B4XPages.MainPage.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) + Log(m) 'ignore +End Sub + +Sub mandamosLoc(coords As String) +' Log("Iniciamos mandamosLoc "&coords) +' Log("locRequest="&locRequest) + If locRequest="Activa" Then 'Si hay solicitud de ubicacion, entonces la mandamos ... + Dim params As Map = CreateMap("topic":Sprvsr,"title":"ubicacionRecibida", "body":coords, "t":"u") + SendMessage(params) + locRequest="Enviada" + CallSubDelayed(Tracker,"CreateLocationRequest") + End If +End Sub + +Sub guardaInfoEnArchivo(coords As String) 'ignore 'Escribimos coordenadas y fecha a un archivo de texto + Log("Guardamos ubicacion en BD") + Dim latlon() As String = Regex.Split(",", coords) + B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO RUTA_GPS(FECHA, LAT, LON) VALUES (?,?,?)", Array As Object (latlon(2),latlon(0),latlon(1))) +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) + B4XPages.MainPage.batt=Level +End Sub + +Sub compress(str As String) As String + ' Compression + Private su As StringUtils + Dim compressed() As Byte = GZip.compress(str) + Log($"CompressedBytesLength: ${compressed.Length}"$) + Dim base64 As String = su.EncodeBase64(compressed) + Log($"CompressedBytes converted to base64 Length: ${base64.Length}"$) + Log($"CompressedBytes converted to base64: ${base64}"$) + Return base64 +End Sub + +Sub decompress(base64 As String) As String 'ignore + ' Decompression + Private su As StringUtils + Dim decompressedbytes() As Byte = su.DecodeBase64(base64) + Log($"decompressedbytesLength: ${decompressedbytes.Length}"$) + Dim bc As ByteConverter + Dim uncompressed As String = bc.StringFromBytes(decompressedbytes,"UTF8") + Log($"uncompressedLength: ${uncompressed.Length}"$) ' 6163 Bytes + Log($"Decompressed String = ${uncompressed}"$) + Return uncompressed +End Sub + +Sub dameRuta As String + Log("dameRuta") + Dim c As Cursor + c = B4XPages.MainPage.skmt.ExecQuery("select LAT, LON from RUTA_GPS order by FECHA desc limit 390") + 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 = B4XPages.MainPage.skmt.ExecQuery("delete FROM RUTA_GPS") +End Sub \ No newline at end of file diff --git a/B4A/Starter.bas b/B4A/Starter.bas new file mode 100644 index 0000000..8552e33 --- /dev/null +++ b/B4A/Starter.bas @@ -0,0 +1,128 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=Service +Version=9.85 +@EndOfDesignText@ +#Region Service Attributes + #StartAtBoot: False + #ExcludeFromLibrary: 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. + Public gps As GPS + Dim ph As Phone + Public rp As RuntimePermissions + Public FLP As FusedLocationProvider +' Private flpStarted As Boolean + Dim reqManager As DBRequestManager + Dim server As String = "http://187.189.244.154:1782" +' Dim server As String = "http://10.0.0.205:1782" + Dim Timer1 As Timer + Dim Interval As Int = 30 + Dim ruta As String = File.DirInternal + 'Para los Logs + Private logs As StringBuilder + Private logcat As LogCat + Dim logger As Boolean = False + Dim marcaCel As String = ph.manufacturer + Dim muestraProgreso = 0 + Private BTAdmin As BluetoothAdmin + Dim MAC_IMPRESORA As String + Dim ubicacionActual As Location + Dim enVenta As Boolean = False + Dim VarX As Int = 0 + Private BTAdmin As BluetoothAdmin + Public BluetoothState As Boolean +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. +' gps.Initialize("GPS") +' CallSubDelayed(FirebaseMessaging, "SubscribeToTopics") 'Para Push FirebaseMessaging +' BTAdmin.Initialize("admin") +' Timer1.Initialize("Timer1", Interval * 1000) +' Timer1.Enabled = True +'' 'Para los Logs +' #if RELEASE +' logcat.LogCatStart(Array As String("-v","raw","*:F","B4A:v"), "logcat") +' #end if +' logs.Initialize +' CallSubDelayed(FirebaseMessaging, "SubscribeToTopics") 'Para Push FirebaseMessaging +' ubicacionActual.Initialize +'End Sub + +Private Sub BTAdmin_StateChanged (NewState As Int, OldState As Int) + If logger Then Log("BT state changed: " & NewState) + BluetoothState = NewState = BTAdmin.STATE_ON +' StateChanged +End Sub + + +'Sub Service_Start (StartingIntent As Intent) +' Service.StopAutomaticForeground 'Starter service can start in the foreground state in some edge cases. +' Subs.revisaBD +' Log(marcaCel) +' reqManager.Initialize(Me, server) +'End Sub + +'Private Sub Timer1_Tick +'' Log("Next run " & DateTime.Time(DateTime.Now + Interval * 1000)) +' ENVIA_ULTIMA_GPS +'End Sub + +Sub GPS_LocationChanged (Location1 As Location) +' CallSub2(Main, "GPS_LocationChanged", Location1) +End Sub + +Sub Service_TaskRemoved + 'This event will be raised when the user removes the app from the recent apps list. +End Sub + +Sub Service_Destroy + +End Sub + +'Sub ENVIA_ULTIMA_GPS +' LogColor("Iniciamos ENVIA_ULTIMA_GPS", Colors.Magenta) +' Dim skmt As SQL +' Dim cmd As DBCommand +' skmt.Initialize(ruta,"kmt.db", True) +'' cmd.Initialize +'' cmd.Name = "select_fechat" +'' B4XPages.MainPage.reqManager.ExecuteQuery(cmd , 0, "fechat") +' Dim cmd As DBCommand +' cmd.Initialize +' cmd.Name = "UPDATE_GUNA_ACTUAL2_GPS" +' cmd.Parameters = Array As Object(B4XPages.MainPage.montoActual, B4XPages.MainPage.clientestotal, B4XPages.MainPage.clientesventa,B4XPages.MainPage.clientesvisitados,B4XPages.MainPage.lat_gps,B4XPages.MainPage.lon_gps,B4XPages.MainPage.batt,0, 0, 0,B4XPages.MainPage.ALMACEN,B4XPages.MainPage.rutapreventa) +'' Log($"montoActual: ${B4XPages.MainPage.montoActual}, cTotal: ${B4XPages.MainPage.clientestotal}, cVenta: ${B4XPages.MainPage.clientesventa}, cVisitados: ${B4XPages.MainPage.clientesvisitados}, ${B4XPages.MainPage.lat_gps}, ${B4XPages.MainPage.lon_gps}, Batt: ${B4XPages.MainPage.batt}, 0, 0, 0, Almacen: ${B4XPages.MainPage.ALMACEN}, Ruta: ${B4XPages.MainPage.rutapreventa}"$) +' reqManager.ExecuteCommand(cmd, "inst_visitas") +' skmt.ExecNonQuery2("Update cat_variables set CAT_VA_VALOR = ? WHERE CAT_VA_DESCRIPCION = ?" , Array As String(DateTime.Time(DateTime.Now),"HoraIngreso")) +' 'Reiniciamos el timer para cuando llamamos el Sub desde "seleccion" +' Timer1.Enabled = False +' Timer1.Interval = Interval * 1000 +' Timer1.Enabled = True +'End Sub + +'Para los Logs +Private Sub logcat_LogCatData (Buffer() As Byte, Length As Int) + logs.Append(BytesToString(Buffer, 0, Length, "utf8")) + If logs.Length > 4000 Then + logs.Remove(0, logs.Length - 2000) 'Obtenemos log de 2000 ~ 4000 chars + End If +End Sub + +''Return true to allow the OS default exceptions handler to handle the uncaught exception. 'Para los Logs +'Sub Application_Error (Error As Exception, StackTrace As String) As Boolean +' 'wait for 500ms to allow the logs to be updated. +' Dim jo As JavaObject +' Dim l As Long = 500: jo.InitializeStatic("java.lang.Thread").RunMethod("sleep", Array(l)) 'Sleep 500ms +' logcat.LogCatStop +' logs.Append(StackTrace) +' Subs.revisaBD +' Subs.errorLog.ExecNonQuery2("INSERT INTO errores(fecha, error) VALUES (?,?)", Array As Object (Subs.fechaKMT(DateTime.now), logs)) +' Return True +'End Sub \ No newline at end of file diff --git a/B4A/Subs.bas b/B4A/Subs.bas new file mode 100644 index 0000000..49ddd17 --- /dev/null +++ b/B4A/Subs.bas @@ -0,0 +1,1388 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=StaticCode +Version=11 +@EndOfDesignText@ +'Code module +'Subs in this code module will be accessible from all modules. +Sub Process_Globals + 'These global variables will be declared once when the application starts. + 'These variables can be accessed from all modules. + Public GZip As GZipStrings '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 wifi As MLwifi + Dim ssid As String 'ignore + Dim rutaMaxPoints As Int = 3000 + Dim rutaHrsAtras As Int = 48 +' Dim rutaInicioHoy As String = "" + Private subsLogs As Boolean = False + Dim skmt As SQL + +End Sub + +'Pone el valor de phn.Model en la variable global "devModel" +Sub getPhnId As String 'ignore + 'Requiere la libreria "Phone" + devModel = phn.Model + If devModel.Length <= 3 Then 'Si phn.Model esta en blanco ... + Dim t As String = phn.GetSettings("android_id") 'Intentamos con "android_id" + devModel = t + End If + If devModel.Length >= 3 Then 'Si tenemos valor para phn.Model + File.WriteString(File.DirInternal, "phnId.txt", devModel) 'Sobreescribimos archivo phnId.txt with deviceId +' Log("Tenemos phnId: "&devModel&" "&File.DirInternal&"/phn.txt sobreescrito") + Else If devModel.Length < 3 Then ' Si no tenemos valor, lo leemos de phnId.txt + Dim s As String = File.ReadString(File.DirInternal, "phnId.txt") + devModel = s +' Log("Leemos id de "&File.DirInternal&"/phnId.txt") +' Log(devModel) + End If + 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) + Dim OrigFormat As String = DateTime.DateFormat 'save orig date format + DateTime.DateFormat="yyMMddHHmmss" + Dim nuevaFecha As String=DateTime.Date(fecha) + DateTime.DateFormat=OrigFormat 'return to orig date format +' Log(nuevaFecha) + Return nuevaFecha +End Sub + +'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 + +'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 + +'Escribimos las coordenadas y fecha a un archivo de texto +Sub guardaInfoEnArchivo(coords As String) 'ignore + ' Cambiamos el formato de la hora + Dim OrigFormat As String=DateTime.DateFormat 'save orig date format + DateTime.DateFormat="MMM-dd HH:mm:ss" + Dim lastUpdate As String=DateTime.Date(DateTime.Now) + DateTime.DateFormat=OrigFormat 'return to orig date format + + Dim ubic As String = coords&","&lastUpdate + Dim out As OutputStream = File.OpenOutput(File.DirRootExternal, "gps.txt", True) + Dim s As String = ubic & CRLF + Dim t() As Byte = s.GetBytes("UTF-8") + out.WriteBytes(t, 0, t.Length) + out.Close +End Sub + +'Escribimos las coordenadas (latitud, longitud, fecha) y fecha a una BD +Sub guardaInfoEnBD(coords As String) 'ignore + Log("Guardamos ubicacion en BD - "&coords) + Try + Dim latlon() As String = Regex.Split("\|", coords) + If latlon.Length < 2 Then latlon = Regex.Split(",", coords) 'Si son menos de 2, entonces estan separadas por comas y no por "|" + If subsLogs Then Log("LatLon="&latlon) + kmt.ExecNonQuery2("INSERT INTO RUTA_GPS(FECHA, LAT, LON) VALUES (?,?,?)", Array As Object (latlon(2),latlon(0),latlon(1))) + Catch + LogColor(LastException, Colors.red) + End Try +End Sub + +''Regresa la ruta solicitada comprimida y en base64 +'Sub dameRuta(inicioRuta As String, origenRuta As String) As String 'ignore +' 'Requiere la libreria "SQL" +' Dim fechaInicio As String +' Try 'incioRuta es numero +' inicioRuta = inicioRuta * 1 +'' Log("fechaInicio numerica="&fechaInicio) +' fechaInicio = fechaKMT(DateTime.Now - (DateTime.TicksPerHour * inicioRuta)) +' Catch 'inicioRuta es string +' fechaInicio = fechaInicioHoy +'' Log("fechaInicio string="&fechaInicio) +' End Try +' If subsLogs Then Log("fechaInicio: "&fechaInicio&" | rutaHrsAtras="&rutaHrsAtras) 'fechaKMT(DateTime.Now) +' Dim c As Cursor +' If kmt.IsInitialized = False Then kmt.Initialize(Starter.ruta, "kmt.db", True) +' If subsLogs Then Log("select FECHA, LAT, LON from "& origenRuta &" where FECHA > " & fechaInicio & " order by FECHA desc limit " & rutaMaxPoints) +' c = kmt.ExecQuery("select FECHA, LAT, LON from "& origenRuta &" where FECHA > " & fechaInicio & " order by FECHA desc limit " & rutaMaxPoints) +' 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")&","&c.GetString("FECHA") +' B4XPages.MainPage.fechaRuta = c.GetString("FECHA") +' Next +' End If +' c.Close +' Return compress(ruta2) +'End Sub + +'Limpiamos la tabla RUTA_GPS de la BD +Sub deleteGPS_DB 'ignore + kmt.ExecNonQuery("delete from RUTA_GPS") + kmt.ExecNonQuery("vacuum;") + ToastMessageShow("Borramos BD Coords GPS", False) +End Sub + +'Limpiamos la tabla errorLog de la BD +Sub deleteErrorLog_DB 'ignore + errorLog.ExecNonQuery("delete from errores") + errorLog.ExecNonQuery("vacuum;") + 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 + +''Revisa que exista la BD y si es necesario crea algunans tablas dentro de ella +'Sub revisaBD 'ignore +'' Main.ruta = File.DirInternal +' If Not(File.Exists(Starter.ruta, "kmt.db")) Then File.Copy(File.DirAssets, "kmt.db", Starter.ruta, "kmt.db") +' If Not(kmt.IsInitialized) Then kmt.Initialize(Starter.ruta, "kmt.db", True) +' kmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS RUTA_GPS(FECHA INTEGER, LAT TEXT, LON TEXT)") +'' kmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS UUC(fecha INTEGER, lat TEXT, lon TEXT)") 'LastKnownLocation +' kmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS bitacora(fecha INTEGER, texto TEXT)") 'Bitacora +' 'Tabla para la bitacora de errores +' If Not(errorLog.IsInitialized) Then errorLog.Initialize(Starter.ruta, "errorLog.db", True) +' errorLog.ExecNonQuery("CREATE TABLE IF NOT EXISTS errores(fecha INTEGER, error TEXT)") +'End Sub + +Sub fechanormal(fecha As String) As String 'ignore +' Log(fecha) + Dim OrigFormat As String = DateTime.DateFormat 'save orig date format + DateTime.DateFormat = "YYYY/MM/dd HH:mm:ss" + Dim nuevaFecha As String=DateTime.Date(fecha) + DateTime.DateFormat = OrigFormat 'return to orig date format +' Log(nuevaFecha) + Return nuevaFecha +End Sub + +'Obtiene el ssid al que esta conectado el telefono +Sub getSSID 'ignore +' 'Requiere la libreria "MLWifi400" +' If wifi.isWifiConnected Then +' ssid = wifi.WifiSSID +' End If +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 +'' Log("Iniciamos mandamosLoc "&coords) +'' Log("locRequest="&Tracker.locRequest) +' guardaInfoEnBD(coords)'Escribimos coordenadas y fecha a una bd +' Dim t As String +' If Tracker.locRequest="Activa" Then +' If PushService.au = 1 Then +' t = "au" ' es una actualizacion +' Else +' t = "u" ' es una peticion +' End If +' Dim params As Map = CreateMap("topic":"Sprvsr", "coords":coords, "t":t, "b":PushService.battery, "mt":Main.montoActual) +' CallSub2(PushService, "mandaMensaje",params) +' Tracker.locRequest="Enviada" +' CallSubDelayed(Tracker,"CreateLocationRequest") +' End If +'End Sub + +'Regresa la fecha y hora de hoy a las 00:00 en el formato "yyMMddHHMMSS" +Sub fechaInicioHoy As String 'ignore + Dim OrigFormat As String = DateTime.DateFormat 'save orig date format + DateTime.DateFormat="yyMMdd" + Private h As String = DateTime.Date(DateTime.Now)&"000000" + DateTime.DateFormat=OrigFormat 'return to orig date format + Log("Hoy="&h) + Return h +End Sub + +'Guardamos "texto" a la bitacora +Sub log2DB(texto As String) 'ignore + LogColor(fechaKMT(DateTime.Now)&" - log2BD: '"&texto&"'", Colors.LightGray) + kmt.ExecNonQuery2("INSERT INTO bitacora(fecha, texto) VALUES (?,?)", Array As Object (fechaKMT(DateTime.now), texto)) +End Sub + +'Regresa verdadero si ya pasaron XX minutos de la fecha dada +Sub masDeXXMins(hora As Int, mins As Int) As Boolean 'ignore + If (hora + mins * DateTime.TicksPerMinute) < DateTime.Now Then + Return True + Else + Return False + End If +End Sub + +'Regresa verdadero si ya pasaron XX minutos de la fechaKMT dada +Sub masDeXXMinsKMT(hora As String, mins As Int) As Boolean 'ignore + Try + ' LogColor($"Hora=${fechaKMT(fechaKMT2Ticks(hora) + mins * DateTime.TicksPerMinute)}, Mins=${mins}, Actual=${fechaKMT(DateTime.Now)}"$,Colors.red) + If fechaKMT2Ticks(hora) + mins * DateTime.TicksPerMinute < DateTime.Now Then + ' Log("+++ +++ "&fechaKMT(fechaKMT2Ticks(hora) + mins * DateTime.TicksPerMinute) & " < " & fechaKMT(DateTime.Now)) + Return True + Else + ' Log("+++ +++ "&fechaKMT(fechaKMT2Ticks(hora) + mins * DateTime.TicksPerMinute) & " > " & fechaKMT(DateTime.Now)) + Return False + End If + Catch + Log(LastException) + End Try +End Sub + +'Limpiamos la tabla "bitacora" de la BD +Sub borraLogDB 'ignore + LogColor("Borramos BD de log", Colors.Magenta) + kmt.ExecNonQuery("delete from bitacora") + kmt.ExecNonQuery("vacuum;") +End Sub + +'Monitoreamos los servicios para ver si estan activos (No pausados), y si no, los reniciamos +'Sub Monitor 'ignore +' Private monitorStatus As Boolean = True +' LogColor("Corriendo Subs.Monitor", Colors.RGB(161,150,0)) +' If IsPaused(Tracker) Then +' log2DB("Reiniciando 'Tracker Pausado' desde Subs.Monitor") +' StartService(Tracker) +' monitorStatus = False +' Else +' CallSubDelayed(Tracker, "revisaFLP") +' End If +' If IsPaused(PushService) Then +' log2DB("Reiniciando 'PushService Pausado' desde Subs.Monitor") +' StartService(PushService) +' monitorStatus = False +' Else +' revisaPushService +' End If +' If monitorStatus Then LogColor(" +++ +++ Servicios Activos", Colors.Green) +'End Sub + +''Compara la UUG (Ultima Ubicacion Guardada) con FLP.LastKnowLocation y si +''cumple con los requisitos de distancia y precision la guardamos en la BD. +'Sub revisaUUG 'ignore +' Try +'' revisaFLP +' If Tracker.FLP.GetLastKnownLocation.IsInitialized Then +' Dim daa As Int = Tracker.UUGCoords.DistanceTo(Tracker.FLP.GetLastKnownLocation) 'Distancia de la UUG a la actual de Tracker.FLP.GetLastKnownLocation +' If Starter.Logger Then LogColor($"**** UUC "${fechaKMT(Tracker.FLP.GetLastKnownLocation.Time)}|$0.2{Tracker.FLP.GetLastKnownLocation.Accuracy}|$0.8{Tracker.FLP.GetLastKnownLocation.Latitude}|$0.8{Tracker.FLP.GetLastKnownLocation.Longitude}|$0.2{Tracker.FLP.GetLastKnownLocation.Speed}|"$, Colors.RGB(255,112,35)) +' If daa > 40 And Tracker.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 ... +' kmt.ExecNonQuery2("INSERT INTO RUTA_GPS(fecha, lat, lon) VALUES (?,?,?)", Array As Object (fechaKMT(Tracker.FLP.GetLastKnownLocation.Time),Tracker.FLP.GetLastKnownLocation.Latitude,Tracker.FLP.GetLastKnownLocation.Longitude)) +' If Starter.Logger Then Log("++++ Distancia a anterior="&daa&"|"&"Precision="&Tracker.FLP.GetLastKnownLocation.Accuracy) +' End If +' Tracker.UUGCoords = Tracker.FLP.GetLastKnownLocation +' End If +' Catch +' LogColor("If Tracker.FLP.GetLastKnownLocation.IsInitialized --> "&LastException, Colors.Red) +' End Try +'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(Tracker.FLP.IsInitialized) Then +' log2DB("revisaFLP: No esta inicializado ... 'Reinicializando FLP'") +' Tracker.FLP.Initialize("flp") +' todoBienFLP = False +' End If +' Catch +' LogColor("If Not(Tracker.FLP.IsInitialized) --- "&LastException, Colors.Red) +' End Try +' Try +' If Tracker.FLP.IsInitialized Then +' Try +' If Not(Tracker.FLP.IsConnected) Then +' log2DB("revisaFLP: No esta conectado ... 'Reconectando FLP'") +' ' Tracker.FLP.Connect +' CallSubDelayed(Tracker,"StartFLP") +' todoBienFLP = False +' End If +' Catch +' LogColor("If Not(Tracker.FLP.IsConnected) --> "&LastException, Colors.Red) +' End Try +' Try +' If Tracker.FLP.IsConnected And _ +' Tracker.FLP.GetLastKnownLocation.IsInitialized And _ +' Tracker.FLP.GetLastKnownLocation.DistanceTo(Tracker.UUGCoords) > 500 Then +' log2DB("revisaFLP: 'No se esta actualizando, lo reiniciamos ...'") +' StartService(Tracker) +' 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 + +'Revisamos que el servicio "PushService" este inicializado y activo +'Sub revisaPushService 'ignore +' Private todoBienPS As Boolean = True +' LogColor("**** **** Revisamos PushService **** ****", Colors.RGB(78,0,227)) +' If Not(PushService.wsh.IsInitialized) Then 'Si no esta inicializado ... +' log2DB("revisaPushService: No esta inicializado ... 'Reinicializando PushService'") +' CallSubDelayed(PushService, "Connect") +' todoBienPS = False +' End If +' If Not(PushService.wsh.ws.Connected) Then 'Si no esta conectado ... +' log2DB("revisaPushService: No esta conectado ... 'Reconectando PushService'") +' CallSubDelayed(PushService, "Connect") +' todoBienPS = False +' End If +' If masDeXXMinsKMT(Starter.pushServiceActividad, 5) Then 'Si mas de xx minutos de la ultima actividad entonces ... +' PushService.wsh.Close +' CallSubDelayed(PushService, "Connect") +'' StartService(PushService) +' log2DB("revisaPushService: 'Reconectamos 'PushService' por inactividad") +' Starter.pushServiceActividad = fechaKMT(DateTime.Now) +' todoBienPS = False +' End If +' If todoBienPS Then LogColor(" +++ +++ Sin errores en PushService", Colors.Green) +'End Sub + +''Borramos renglones extra de la tabla de errores +'Sub borraArribaDe100Errores 'ignore +' revisaBD +' LogColor("Borramos BD de log", Colors.Magenta) +' errorLog.ExecNonQuery("DELETE FROM errores WHERE fecha NOT in (SELECT fecha FROM errores ORDER BY fecha desc LIMIT 99 )") +' errorLog.ExecNonQuery("vacuum;") +' Log("Borramos mas de 100 de errorLog") +'End Sub + +''Borramos renglones extra de la tabla de bitacora +'Sub borraArribaDe600RenglonesBitacora 'ignore +' revisaBD +' If Starter.logger Then LogColor("Recortamos la tabla de la Bitacora, limite de 600", Colors.Magenta) +' Private c As Cursor +' c = B4XPages.MainPage.skmt.ExecQuery("select fecha from bitacora") +' c.Position = 0 +' If c.RowCount > 650 Then +' B4XPages.MainPage.skmt.ExecNonQuery("DELETE FROM bitacora WHERE fecha NOT in (SELECT fecha FROM bitacora ORDER BY fecha desc LIMIT 599 )") +' B4XPages.MainPage.skmt.ExecNonQuery("vacuum;") +'' if starter.logger then Log("Borramos mas de 600 de bitacora") +' End If +' c.Close +'End Sub + +''Inserta 50 renglones de prueba a la tabla "errores" +'Sub insertaRenglonesPruebaEnErrorLog 'ignore +' revisaBD +' Log("insertamos 50 renglones a errorLog") +' For x = 1 To 50 +' errorLog.ExecNonQuery2("INSERT INTO errores(fecha, error) VALUES (?,?)", Array As Object (fechaKMT(DateTime.now), "abc")) +' Log(x) +' Next +'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 + 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 + +Sub InstallAPK(dir As String, apk As String) 'ignore + If File.Exists(dir, apk) Then + Dim i As Intent + i.Initialize(i.ACTION_VIEW, "file://" & File.Combine(dir, apk)) + i.SetType("application/vnd.android.package-archive") + StartActivity(i) + End If +End Sub + +'Copia la base de datos del almacenamiento interno al externo en el directorio kmts +Sub copiaDB(result As Boolean) 'ignore + ToastMessageShow("copiaDB", False) + If result Then + Dim p As String + If File.ExternalWritable Then + p = File.DirRootExternal +' Log("Externo") + Else + p = File.DirInternal +' Log("Interno") + End If + Dim theDir As String + Try + File.MakeDir(File.DirRootExternal,"kmts") + theDir = "/kmts" + Catch + theDir = "" + End Try + Try + File.Copy(File.DirInternal,"kmt.db",File.DirRootExternal&theDir,"cedex_kmt.db") + File.Copy(File.DirInternal,"errorLog.db",File.DirRootExternal&theDir,"cedex_errorLog.db") + ToastMessageShow("BD copiada!", False) + Catch + ToastMessageShow("No se pudo hacer la copia: "&LastException, True) + End Try + Log("rootExternal="&p) + Log("File.DirInternal="&File.DirInternal) + Log("File.DirRootExternal="&File.DirRootExternal) + Else + ToastMessageShow("Sin permisos", False) + End If +End Sub + +'Hace visible y trae al frente el panel con los parametros "Top" y "Left" dados +Sub panelVisible(panel As Panel, top As Int, left As Int) 'ignore + panel.BringToFront + panel.Visible = True + panel.Top = top + panel.Left = left +End Sub + +'Centra una etiqueta dentro de un elemento superior +Sub centraEtiqueta(elemento As Label, anchoElementoSuperior As Int) 'ignore + elemento.Left = Round(anchoElementoSuperior/2)-(elemento.Width/2) +End Sub + +'Centra un panel horizontalmente dentro de un elemento superior +Sub centraPanel(elemento As Panel, anchoElementoSuperior As Int) 'ignore + elemento.Left = Round(anchoElementoSuperior/2)-(elemento.Width/2) +End Sub + +'Centra un panel verticalmente dentro de un elemento superior +Sub centraPanelV(elemento As Panel, altoElementoSuperior As Int) 'ignore + elemento.Top = Round(altoElementoSuperior/2)-(elemento.Height/2) +End Sub + +'Centra una barra de progreso dentro de un elemento superior +Sub centraProgressBar(elemento As ProgressBar, anchoElementoSuperior As Int) 'ignore + elemento.Left = Round(anchoElementoSuperior/2)-(elemento.Width/2) +End Sub + +Sub centraEditText(elemento As EditText, anchoElementoSuperior As Int) 'ignore + elemento.Left = Round(anchoElementoSuperior/2)-(elemento.Width/2) +End Sub + +'Regresa el usuario de la tabla USUARIOA si es que existe, si no existe, regresa "SinUsuario". +Sub buscaDBUsuario As String 'ignore + Private c As Cursor + Private usuario As String = "SinUsuario" + c=kmt.ExecQuery("select USUARIO from usuarioa") + c.Position=0 + If c.RowCount > 0 Then usuario = c.GetString("USUARIO") + Return usuario +End Sub + +''Saca el usuario de la tabla USUARIOA +'Sub dameUsuarioDeDB As String 'ignore +' Private c As Cursor +' Private u As String = "SinUsuario" +' If Not(kmt.IsInitialized) Then revisaBD +' c=kmt.ExecQuery("select USUARIO from usuarioa") +' c.Position=0 +' If c.RowCount > 0 Then u = c.GetString("USUARIO") +' c.Close +' Return u +'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_info2 set gestion = 2 where CAT_CL_CODIGO In (select cuenta from cuentaa)") +' c.Close + ToastMessageShow("guardaProdSin", False) +End Sub + +'Regresa el almacen actual de la base de datos. +Sub traeAlmacen As String 'ignore + Private c As Cursor + Private a As String + c=B4XPages.MainPage.skmt.ExecQuery("select ID_ALMACEN from CAT_ALMACEN") + c.Position = 0 + a = C.GetString("ID_ALMACEN") + c.Close + Return a +End Sub + +'Regresa el nombre del producto desde CAT_GUNAPROD +Sub traeProdNombre(id As String) As String + Private h As Cursor + Private n As String + h=B4XPages.MainPage.skmt.ExecQuery2("select CAT_GP_NOMBRE from CAT_GUNAPROD where CAT_GP_ID = ? ", Array As String(id.Trim)) + If h.RowCount > 0 Then + h.Position = 0 + n = h.GetString("CAT_GP_NOMBRE") +' Log(h.RowCount&"|"&id&"|"&n&"|") + End If + h.Close + If n = Null Or n="" Then n = "N/A" +' Log(h.RowCount&"|"&id&"|"&n&"|") + Return n +End Sub + +'Regresa la ruta actual de la base de datos. +Sub traeRuta As String 'ignore + Private c As Cursor + Private r As String + c=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_RUTA from kmt_info2 where CAT_CL_CODIGO In (Select cuenta from cuentaa)") + r = "0" + If c.RowCount > 0 Then + c.Position=0 + r = c.GetString("CAT_CL_RUTA") + End If + c.Close + Return r +End Sub + +Sub traeCliente As String 'ignore + Private c As Cursor + Private cl As String + c=B4XPages.MainPage.skmt.ExecQuery("Select CUENTA from cuentaa") + c.Position=0 + cl = c.GetString("CUENTA") + c.Close + Return cl +End Sub + +Sub CalcularCosto(minutos As Int, tarifa_por_hora As Int) As Int + Dim costo As Int = 0 + + If minutos <= 0 Then + Return costo + End If + + If minutos <= 15 Then + costo = tarifa_por_hora / 4 + Else If minutos <= 30 Then + costo = tarifa_por_hora / 2 + Else If minutos <= 45 Then + costo = (tarifa_por_hora * 3) / 4 + Else If minutos <= 60 Then + costo = tarifa_por_hora + Else + + Dim horas As Int = Floor(minutos / 60) + costo = horas * tarifa_por_hora + minutos = minutos Mod 60 + + If minutos <= 15 Then + costo = costo + tarifa_por_hora / 4 + Else If minutos <= 30 Then + costo = costo + tarifa_por_hora / 2 + Else If minutos <= 45 Then + costo = costo + (tarifa_por_hora * 3) / 4 + Else If minutos <= 60 Then + costo = costo + tarifa_por_hora + End If + End If + + Return costo +End Sub + + +Sub traeFecha As String 'ignore + DateTime.DateFormat = "dd/MM/yyyy" + Private sDate As String =DateTime.Date(DateTime.Now) + Private sTime As String =DateTime.Time(DateTime.Now) + Return sDate & " " & sTime +End Sub + +''Regresa el usuario de la tabla USUARIOA +'Sub traeUsuarioDeBD As String 'ignore +' Private c As Cursor +' Private u As String = "SinUsuario" +' If Not(kmt.IsInitialized) Then revisaBD +' c=kmt.ExecQuery("select USUARIO from usuarioa") +' c.Position=0 +' If c.RowCount > 0 Then u = c.GetString("USUARIO") +' c.Close +' Return u +'End Sub + +'Regresa verdadero si hay pedido en la tabla "PEDIDO" del cliente actual. +Sub hayPedido As Boolean + Private thisC As Cursor=B4XPages.MainPage.skmt.ExecQuery($"select count(PE_CLIENTE) as hayPedido from PEDIDO where PE_CLIENTE = '${traeCliente}'"$) + thisC.Position=0 + Private hay As Boolean = False + If thisC.GetInt("hayPedido") > 0 Then hay = True +' Log($"Cliente actual=${traeCliente}, hayPedido=${hay}"$) + Return hay +End Sub + +'Sub guardaProducto(cedis 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, tipoVenta As String) +' LogColor("guardaProducto: "&prodId&", cant="&cant&" - TV:"&tipoVenta, Colors.Magenta) +' Private c As Cursor +' 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_FOLIO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (cedis, (cant * costoU), costoU, cant, nombre, prodId, clienteId, fecha, usuario, rutaV, precioSin, tipoVenta)) +' B4XPages.MainPage.skmt.ExecNonQuery2("update cat_gunaprod set cat_gp_almacen = cat_gp_almacen - ? where cat_gp_id = ? ", Array As Object(cant, prodId)) +' c=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, fecha, usuario, c.GetString("CANT_CLIE"), c.GetString("TOTAL_CLIE"), B4XPages.MainPage.lon_gps, B4XPages.MainPage.lat_gps, cedis, c.GetString("TOTAL_CLIE_SIN"))) +' B4XPages.MainPage.skmt.ExecNonQuery("UPDATE kmt_info2 set gestion = 2 where CAT_CL_CODIGO In (select cuenta from cuentaa)") +'End Sub + + +'Regresa un mapa con la información de la promo. +'Regresa: {id, maxXcliente, maxRecurrente, maxPromos, historico, +' productos={idProducto={idProducto, preciosimptos, precio, almacen, tipo, piezas, usuario, fecha, regalo, clasif}} 'Mapa con los productos de la promo y los datos de cada uno. +' tipos={idProducto=tipo} 'Mapa con id y tipo del producto, 0 si es fijo y 1 si es variable. +' prodsFijos={idProducto,idProducto} 'Lista con los ids de los productos fijos. +' prodsVariables={idProducto,idProducto} 'Lista con los ids de los productos variables. +' resultado="OK" 'Ok si existe la promocion. +' prodsVariablesRequeridos=5} 'Cantidad de productos variables requeridos para la promoción. +Sub traePromo(promo As String, cliente As String) As Map + Log($"TRAE PROMO = ${promo}"$) + Private inicioContador As String = DateTime.Now + Private c As Cursor = B4XPages.MainPage.skmt.ExecQuery("Select * from promos_comp where cat_pa_id = '"& promo&"'") 'Obtenemos las el maximo de promocioones a otorgar. + Private siHistorico As String = 0 + Private promoMap As Map + Private prodsFijos, prodsFijosPrecios, prodsFijosPiezas, prodsVariables As List + promoMap.Initialize + prodsFijos.Initialize + prodsFijosPrecios.Initialize + prodsFijosPiezas.Initialize + prodsVariables.Initialize + c.Position = 0 + If c.RowCount > 0 Then promoMap = CreateMap("id":promo, "maxXcliente":c.GetString("CAT_PA_MAXPROMCLIE"), "maxRecurrente":c.GetString("CAT_PA_MAXPROMREC"), "maxPromos":c.GetString("CAT_PA_MAXPROM")) + c = B4XPages.MainPage.skmt.ExecQuery("Select count(*) as hist from HIST_PROMOS where HP_CLIENTE = '"& cliente & "' and HP_CODIGO_PROMOCION = '" & promo & "'") 'Revisamos si hay historico de la promoción. + c.Position = 0 + If c.GetString("hist") > 0 Then siHistorico = 1 + promoMap.Put("historico", siHistorico) +' c = B4XPages.MainPage.skmt.ExecQuery("Select * from CAT_DETALLES_PAQ where CAT_DP_ID = '"& promo & "'") 'Obtenemos los detalles de la promoción. + c = B4XPages.MainPage.skmt.ExecQuery("Select * from CAT_DETALLES_PAQ where CAT_DP_ID = '"& promo & "' order by cat_dp_tipo asc") + c.Position = 0 + If c.RowCount > 0 Then + Private prods, tipos As Map + prods.Initialize + tipos.Initialize + For i=0 To c.RowCount -1 + c.Position=i + prods.Put(c.GetString("CAT_DP_IDPROD"), CreateMap("idProducto":c.GetString("CAT_DP_IDPROD"), "precioSimptos":c.GetString("CAT_DP_PRECIO_SIMPTOS"), "precio":c.GetString("CAT_DP_PRECIO"), "almacen":c.GetString("CAT_DP_ALMACEN"), "tipo":c.GetString("CAT_DP_TIPO"), "piezas":c.GetString("CAT_DP_PZAS"), "usuario":c.GetString("CAT_DP_USUARIO"), "regalo":c.GetString("CAT_DP_REGALO"), "clasif":c.GetString("CAT_DP_CLASIF"))) + tipos.Put(c.GetString("CAT_DP_IDPROD"), c.GetString("CAT_DP_TIPO")) + If c.GetString("CAT_DP_TIPO") = "0" Then + prodsFijos.Add(c.GetString("CAT_DP_IDPROD")) + prodsFijosPrecios.Add(c.GetString("CAT_DP_PRECIO")) + prodsFijosPiezas.Add(c.GetString("CAT_DP_PZAS")) + End If + If c.GetString("CAT_DP_TIPO") = "1" Then prodsVariables.Add(c.GetString("CAT_DP_IDPROD")) +' Log($"id:${c.GetString("CAT_DP_IDPROD")}, tipo:${c.GetString("CAT_DP_TIPO")}"$) + Next + promoMap.Put("productos", prods) 'Mapa con los productos de la promocion (id, precio, almacen, tipo, piezas, etc.) + promoMap.Put("tipos", tipos) 'Mapa con los productos de la promoción y su tipo (fijo o variable). + promoMap.Put("prodsFijos", prodsFijos) 'Lista de los productos fijos de la promoción. + promoMap.Put("prodsVariables", prodsVariables) 'Lista de los productos variables de la promoción. + promoMap.Put("prodsFijosCant", prodsFijos.Size) + promoMap.Put("prodsFijosPrecios", prodsFijosPrecios) + promoMap.Put("prodsFijosPiezas", prodsFijosPiezas) + promoMap.Put("prodsVariablesCant", prodsVariables.Size) + promoMap.Put("resultado", "ok") + Else + promoMap.Put("resultado", "No hay datos de la promoción.") + End If + + + c = B4XPages.MainPage.skmt.ExecQuery("Select CAT_GP_STS, CAT_GP_NOMBRE from CAT_GUNAPROD where CAT_GP_ID = '"& promo & "'") 'Obtenemos las piezas requeridas de productos variables para la promoción. + + c.Position = 0 + Private pvr As String = 0 + If c.RowCount > 0 Then + c.Position = 0 + pvr = c.GetString("CAT_GP_STS") + promoMap.Put("prodsVariablesRequeridos", pvr) 'Cantidad de productos variables requeridos para la promoción. + promoMap.put("descripcion", c.GetString("CAT_GP_NOMBRE")) + End If + c.Close +' Log($"Inv variables: ${cuantosVariablesTengoBD(promo)}"$) +' Log($"Inv dispo: ${traemosInventarioDisponibleParaPromo(promo)}"$) +' LogColor($"Promo ${promo}: ${promoMap}"$, Colors.Green) +' LogColor("TIEMPO para traePromo -=" & promo & "=- : " & ((DateTime.Now-inicioContador)/1000), Colors.Red) + Return promoMap +End Sub + +'Regresa un mapa con el inventario disponible por producto para la promoción (desde la base de datos). +Sub traemosInventarioDisponibleParaPromo(promo As String) As Map 'ignore + Private c As Cursor + c = B4XPages.MainPage.skmt.ExecQuery2("SELECT CAT_GP_ID, CAT_GP_ALMACEN FROM CAT_GUNAPROD WHERE CAT_GP_ID IN (select CAT_DP_IDPROD FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID = ?)", Array As String(promo)) +' Private prodInv As Map +' prodInv.Initialize + Private prods As Map + prods.Initialize + If c.RowCount > 0 Then + For i=0 To c.RowCount -1 + c.Position=i + prods.Put(c.GetString("CAT_GP_ID"), c.GetString("CAT_GP_ALMACEN")) +' Log($"prod:${c.GetString("CAT_GP_ID")}, inventario:${c.GetString("CAT_GP_ALMACEN")}"$) + Next +' prodInv.Put("inventarios", prods) + End If + Return prods +End Sub + +'Resta los productos fijos del inventario de la promoción (mapa) y regresa un mapa con el nuevo inventario. +'Hay que darle como parametro un mapa (traePromo(promo)) con toda la informacion de la promocion. +'Regresa en el mapa la llave "resultado" que nos da "ok" o "No hay suficiente producto para la promocion". +Sub restaFijosPromo(promoMap As Map) As Map 'ignore + Private thisLog As Boolean = False 'Si es verdadero, muestra los logs de este sub. + Private inventariosDisponiblesParaEstaPromo As Map = traemosInventarioDisponibleParaPromo(promoMap.Get("id")) 'Obtenemos un mapa con el inventario disponible para cada producto de la promocion desde la base de datos. + If thisLog Then LogColor(inventariosDisponiblesParaEstaPromo, Colors.red) + If thisLog Then LogColor("Inventario inicial antes de FIJOS: "&inventariosDisponiblesParaEstaPromo, Colors.Gray) 'Inventario inicial. + Private i As Int + Private prodsmap As Map = promoMap.Get("productos") 'Obtenemos un mapa con todos los productos de la promoción. + Private prodsFijos As List = promoMap.get("prodsFijos") 'Obtenemos una lista con los productos fijos de la promoción. + For p = 0 To prodsFijos.Size - 1 + Private t As String = prodsFijos.Get(p) 'Obtenemos el Id de este producto desde la lista de productos fijos. + Private p2 As Map = prodsmap.Get(t) 'Obtenemos un mapa con los datos de este producto (id, precio, almacen, tipo, piezas, etc.) + If thisLog Then Log($"T: ${t}, prod ${p2.Get("idProducto")}, piezas: ${p2.Get("piezas")}"$) 'Producto y piezas requeridas + If thisLog Then Log("inventariosDisponiblesParaEstaPromo="&inventariosDisponiblesParaEstaPromo) + If inventariosDisponiblesParaEstaPromo.ContainsKey(t) Then 'Si el mapa del inventario contiene el id del producto entonces ... + i = inventariosDisponiblesParaEstaPromo.get(t) 'Obtenemos del mapa el inventario de este producto. + If thisLog Then Log($"Nuevo inventario de ${t}: ${i}-${promoMap.Get("prodsFijosPiezas").As(List).get(p)} = $1.0{i - promoMap.Get("prodsFijosPiezas").As(List).get(p)}"$) 'El nuevo inventario. + inventariosDisponiblesParaEstaPromo.Put(t, $"${i - promoMap.Get("prodsFijosPiezas").As(List).get(p)}"$) 'Restamos del inventario las piezas requeridas para la promoción y guardamos el nuevo inventario en el mapa. + inventariosDisponiblesParaEstaPromo.Put("resultado", "ok") + Else 'Si en el mapa no esta el id del producto, entonces no tenemos inventario. + inventariosDisponiblesParaEstaPromo.Put("resultado", "No hay suficiente producto para la promocion.") + LogColor("Sin suficiente inventario fijo: " & t, Colors.Blue) + Exit + End If + If i - p2.Get("piezas") < 0 Then + inventariosDisponiblesParaEstaPromo.Put("resultado", "No hay suficiente producto para la promocion.") 'Si el inventario de este producto sale negativo, quiere decir que no tenemos suficiente inventario para la promoción. + Exit + End If + Next + If prodsFijos.Size = 0 Then inventariosDisponiblesParaEstaPromo.Put("resultado", "ok") 'No hay productos fijos. + If thisLog Then LogColor("Inventario final depues de FIJOS: "&inventariosDisponiblesParaEstaPromo, Colors.blue) 'Inventario final. + Return inventariosDisponiblesParaEstaPromo +End Sub + +'Revisa si tenemos los productos variables requeridos para la promoción (mapa). +'Hay que darle como parametro un mapa (traePromo(promo)) con toda la informacion de la promocion. +Sub alcanzanLosVariablesParaPromo(promoMap As Map, inventarioSinFijos As Map) As Boolean 'ignore + Private thisLog As Boolean = False 'Si es verdadero, muestra los logs de este sub. + If thisLog Then LogColor("Inventario inicial: "&inventarioSinFijos, Colors.Gray) 'Inventario inicial. + Private totalProdsVariables As Int = 0 +' Private prodsmap As Map = promoMap.Get("productos") 'Obtenemos un mapa con todos los productos de la promoción. + Private prodsVariables As List = promoMap.get("prodsVariables") 'Obtenemos un a lista con los productos variables de la promoción. + For p = 0 To prodsVariables.Size - 1 + Private t As String = prodsVariables.Get(p) 'Obtenemos el Id de este producto desde la lista de productos fijos. + If inventarioSinFijos.ContainsKey(t) Then 'Si existe el producto en la lista del inventario, entonces ... + Private p2 As String = inventarioSinFijos.Get(t) 'Obtenemos el inventario disponible este producto. + totalProdsVariables = totalProdsVariables + p2 + If thisLog Then Log($"prod ${t}, hay: ${p2}"$) 'Producto y piezas requeridas + End If + Next + If thisLog Then Log("Total prods variables=" & totalProdsVariables & ", requeridos=" & promoMap.Get("prodsVariablesRequeridos")) + Private res As Boolean = False + If totalProdsVariables >= promoMap.Get("prodsVariablesRequeridos") Then res = True 'Si el total de inventario de productos variables (totalProdsVariables) es mayor o igual a los productos requeridos entonces regresamos TRUE + Return res +End Sub + +'Regresa el numero máximo de promociones permitidas, tomando en cuenta recurrentes, clientes y maxPromos. +Sub traeMaxPromos(pm As Map) As Int + Private thisLog As Boolean = True 'Si es verdadero, muestra los logs de este sub. + Private maxPromos As List + Private vendidas As Int = 0 + maxPromos.Initialize +' If Starter.promosLog Then Log("==== HISTORICO:"&pm.Get("historico")) + If thisLog Then Log(pm) + If pm.Get("historico") = "1" Then maxPromos.Add(pm.Get("maxRecurrente")) 'Si hay historico, agregamos maxRecurrente + maxPromos.Add(pm.Get("maxPromos")) 'Agregamos maxPromos + maxPromos.Add(pm.Get("maxXcliente")) 'Agregamos maxXcliente + If thisLog Then Log(maxPromos) + maxPromos.Sort(True) + +' Log($"|${pm.Get("id").As(String).trim}|${traeCliente.Trim}|"$) + Private c As Cursor = B4XPages.MainPage.skmt.ExecQuery2("select sum(PE_CANT) as vendidas from PEDIDO where PE_PROID = ? and PE_CLIENTE = ? ", Array As String(pm.Get("id").As(String).trim, traeCliente.Trim)) + If c.RowCount > 0 Then + c.Position = 0 + vendidas = c.GetInt("vendidas") +' Log(vendidas) + End If + +' If Starter.promosLog Then Log(maxPromos) +' If Starter.promosLog Then Log("Max Promos="&maxPromos.Get(0)) +' LogColor($"maxPromos=${maxPromos.Get(0)} - vendidas=${vendidas}"$, Colors.red) + Return maxPromos.Get(0) - vendidas 'Regresamos el numero mas pequeño de las opciones. +End Sub + +'Regresa la cantidad de promos que se le han vendido al cliente. +Sub traePromosVendidas(promo As String, cliente As String) As Int + Private c As Cursor + Private pv As Int = 0 + c=B4XPages.MainPage.skmt.ExecQuery($"select PE_CANT from PEDIDO where PE_PROID = '${promo}' and PE_CLIENTE = '${cliente}'"$) + If c.RowCount > 0 Then + c.Position = 0 + pv = c.GetInt("PE_CANT") + End If + Return pv +End Sub + +Sub procesaPromocion(idPromo As String, cliente As String) As Map 'ignore + Private thisLog As Boolean = False 'Si es verdadero, muestra los logs de este sub. + Private inicioContador As String = DateTime.Now + If thisLog Then LogColor($"********* Iniciamos revision de Promo ${idPromo} *********"$, Colors.Magenta) + 'Obtenemos el mapa con toda la info de la promoción. + Private pm As Map = traePromo(idPromo, cliente) + If thisLog Then LogColor(pm, Colors.Blue) + If pm.Get("resultado") = "ok" Then 'Si encontramos la promoción, entonces ... + 'Buscamos el máximo de promociones permitidas. + If thisLog Then LogColor($"Promociones permitidas=${traeMaxPromos(pm)}"$, Colors.Blue) + If thisLog Then Log("Promos vendidas: " & traePromosVendidas(idPromo, cliente)) + If traePromosVendidas(idPromo, cliente) >= traeMaxPromos(pm) Then + If thisLog Then LogColor("Ya se vendieron las promos PERMITIDAS para el cliente", Colors.red) + Return CreateMap("status":"ko", "mp":pm) + End If + 'Restamos del inventario (mapa) las piezas necesarias para los productos fijos. + Private inventarioSinFijos As Map = restaFijosPromo(pm) + If thisLog Then LogColor("inventariosfijos="&inventarioSinFijos, Colors.Green) + + If inventarioSinFijos.Get("resultado") = "ok" Then + 'Revisamos que los productos variables requeridos sean menos que el inventario total (mapa). + Private pv As Boolean = alcanzanLosVariablesParaPromo(pm, inventarioSinFijos) + If thisLog Then Log("Alcanzan los variables? --> " & pv) + If pv Then Return CreateMap("status":"ok", "mp":pm) Else Return CreateMap("status":"ko", "mp":pm) + Else + If thisLog Then LogColor("NO HAY INVENTARIO SUFICIENTE " & idPromo, Colors.red) + Return CreateMap("status":"ko", "mp":pm) + End If + End If + ' Si tenemos suficiente inventario para los variables mostramos la promocion, si no ... + ' break 'NO HAY INVENTARIO SUFICIENTE PARA LA PROMOCION. + + LogColor("TIEMPO DE PROCESO ESTA PROMO: " & ((DateTime.Now-inicioContador)/1000), Colors.Red) +End Sub + +'Regresa cuantas promos alcanzan con los productos FIJOS que hay en inventario. +Sub revisaMaxPromosProdsFijosPorInventario2(pm As Map) As Int + Private thisLog As Boolean = False + If thisLog Then Log($"pm=${pm}"$) +' Private prodsFijos As List = pm.get("prodsFijos") + Private invDispParaPromo As Map = traemosInventarioDisponibleParaPromo(pm.Get("id")) + If thisLog Then Log($"invDispParaPromo=${invDispParaPromo}"$) + Private maxPromos As String = traeMaxPromos(pm) + Private maxPromosFijosXinv As Int = 1 + Private fpf2, pdp2 As Int + Private salir As Boolean = False + Private pf As List = pm.Get("prodsFijos") + Private pfp As List = pm.Get("prodsFijosPiezas") + If thisLog Then Log($"maxPromos=${maxPromos}, prodsFijos=${pf}, piezas=${pfp}"$) + If thisLog Then LogColor($"InvFijo disponible=${invDispParaPromo}"$, Colors.Blue) + Private invFijoXpromo As Map + invFijoXpromo.Initialize + For p = 0 To pf.Size -1 'Generamos mapa con los productos fijo y piezas requeridos por promo. + invFijoXpromo.Put(pf.Get(p), pfp.Get(p)) + Next + If thisLog Then LogColor("Inv req. de prods fijos x promo" & invFijoXpromo, Colors.Green) + For i = 1 To maxPromos 'Revisamos cuantas promociones alcanzan, hasta llegar al máximo de promos permitadas. + If thisLog Then LogColor("Prods para promo " & (i+1), Colors.Magenta) + For q = 0 To pf.Size - 1 + Private q2 As String = pf.Get(q) + If thisLog Then Log("q="&q2) +' fpf2 = invFijoXpromo.Get(q2) * i 'Multiplicamos las piezas requeridas por la cantidad de promos. + fpf2 = pfp.Get(q) * i 'Multiplicamos las piezas requeridas por la cantidad de promos. + pdp2 = invDispParaPromo.Get(q2) + If thisLog Then Log($"pf=${q2}, Actual=${(i)}, max promos: ${pdp2}-${fpf2}=${pdp2 - fpf2}"$) + If pdp2 - fpf2 < 0 Then 'Si el inventario es negativo, entonces ya no alcanza para este producto. + salir=True + Exit + End If + Next + If salir Then Exit + maxPromosFijosXinv = i + Next + If thisLog Then LogColor("InvFijo requerido x promo="&invFijoXpromo, Colors.blue) + LogColor("Maximo de promociones de prodsFijos POR inventario = " & maxPromosFijosXinv, Colors.Red) + Return maxPromosFijosXinv +End Sub + +'Regresa cuantas promos alcanzan con los productos FIJOS que hay en inventario. +Sub revisaMaxPromosProdsFijosPorInventario(pm As Map) As Int + Private thisLog As Boolean = False + Private invFijoXpromo As Map + Private t As List + t.Initialize + t.Add(traeMaxPromos(pm)) ' Agregamos a la lista las promos maximas permitidas (recurrente, cliente y promo). + invFijoXpromo.Initialize + If thisLog Then LogColor($"pm=${pm}"$, Colors.Blue) + Private invDispParaPromo As Map = traemosInventarioDisponibleParaPromo(pm.Get("id")) + If thisLog Then Log($"invDispParaPromo=${invDispParaPromo}"$) + Private prodsFijosPiezas As List = pm.Get("prodsFijosPiezas") + Private idProdsFijos As List = pm.Get("prodsFijos") + For p = 0 To idProdsFijos.Size -1 'Generamos una lista con las promos disponibles por producto (dividimos el inventario total entre las piezas requeridas). + If thisLog Then Log($"id=${idProdsFijos.Get(p)}, inv=${invDispParaPromo.Get(idProdsFijos.Get(p))}, pzas=${prodsFijosPiezas.Get(p)}"$) + If thisLog Then Log($"${(invDispParaPromo.Get(idProdsFijos.Get(p)) / prodsFijosPiezas.Get(p))}"$) + Private x() As String = Regex.Split("\.", $"${(invDispParaPromo.Get(idProdsFijos.Get(p)) / prodsFijosPiezas.Get(p))}"$) 'Separamos el resultado de la division por el punto decimal. + If thisLog Then Log(x(0)) + t.Add(x(0).As(Int)) 'Solo guardamos la parte del entero de la division. + Next + t.Sort(True) 'Ordenamos la lista para que en el lugar 0 este el resultao mas pequeño. + If thisLog Then LogColor($"prodsFijos=${idProdsFijos}"$, Colors.Blue) + If thisLog Then LogColor($"prodsFijosPiezasReq=${prodsFijosPiezas}"$, Colors.Blue) + If thisLog Then LogColor($"invFijoXpromo=${invFijoXpromo}"$, Colors.Blue) + LogColor("Max promos de prodsFijos POR inventario = " & t.Get(0), Colors.red) + Return t.Get(0) 'Regresamos el resultado mas pequeño. +End Sub + +'Regresa cuantas promos alcanzan con los productos VARIABLES que hay en inventario. +'La cantidad de promos disponibles se calcula DESPUES de descontar los productos fijos, y si las +'promos por productos fijos llega al maximo, aunque se puedan mas de producos variables, solo se +'regresa el maximo por productos fijos. Ej. si las promos por variables es 10, pero el maximo por +'fijos es 5, entonces regresamos 5. +Sub revisaMaxPromosProdsVariablesPorInventario(pm As Map) As Int 'ignore + Private thisLog As Boolean = False + If thisLog Then Log("======================================================") + If thisLog Then Log("======================================================") + Private invFijoXpromo As Map + invFijoXpromo.Initialize + Private totalProdsVariablesDisponibles As Int = 0 + If thisLog Then LogColor($"pm=${pm}"$, Colors.Blue) + Private invDispParaPromo As Map = traemosInventarioDisponibleParaPromo(pm.Get("id")) + If thisLog Then Log($"invDispParaPromo=${invDispParaPromo}"$) + Private maxPromos As String = traeMaxPromos(pm) + Private maxPromosXFijos As Int = revisaMaxPromosProdsFijosPorInventario(pm) + Private idProdsVariables As List = pm.Get("prodsVariables") + Private prodsVariablesRequeridos As Int = pm.Get("prodsVariablesRequeridos") + Private prodsFijosPiezas As List = pm.Get("prodsFijosPiezas") + Private idProdsFijos As List = pm.Get("prodsFijos") + For p = 0 To idProdsFijos.Size -1 'Generamos mapa con los productos fijos y piezas requeridas por promo. + invFijoXpromo.Put(idProdsFijos.Get(p), prodsFijosPiezas.Get(p)) + Private idEsteProd As String = idProdsFijos.Get(p) + Private invEsteProd As Int = invDispParaPromo.Get(idEsteProd) + Private pzasReqEsteProd As Int = prodsFijosPiezas.Get(p) + If thisLog Then Log($"id=${idEsteProd}, inv=${invEsteProd}, pzas=${pzasReqEsteProd}"$) +' invDispParaPromo.Put( idEsteProd, (invEsteProd - (1)) ) + Next + If thisLog Then LogColor($"MaxPromos=${maxPromos}, promosXFijos=${maxPromosXFijos}"$, Colors.Blue) + If thisLog Then LogColor($"prodsFijos=${idProdsFijos}"$, Colors.Blue) + If thisLog Then LogColor($"prodsFijosPiezasReq=${prodsFijosPiezas}"$, Colors.Blue) + If thisLog Then LogColor($"prodsVariables=${idProdsVariables}${CRLF}Variables Req=${prodsVariablesRequeridos} "$, Colors.Blue) + If thisLog Then LogColor($"invFijoXpromo=${invFijoXpromo}"$, Colors.Blue) + If thisLog Then Log($"Prods variables disponibles = ${totalProdsVariablesDisponibles}"$) + Private maxPromosXVariables As Int = 0 + For x = 1 To maxPromosXFijos + If thisLog Then Log("=====================================================") + If thisLog Then Log("=====================================================") + For i = 0 To idProdsFijos.Size - 1 + If thisLog Then Log($"FIJO - ${idProdsFijos.Get(i)}, ${invDispParaPromo.Get(idProdsFijos.Get(i))} - ${prodsFijosPiezas.Get(i).As(Int)*(i+1)}"$) + invDispParaPromo.Put(idProdsFijos.Get(i), invDispParaPromo.Get(idProdsFijos.Get(i)).As(Int) - prodsFijosPiezas.Get(i).As(Int)*(i+1)) 'Restamos las piezas de los productos fijos del inventario disponible. + Next + If thisLog Then LogColor("Inv disponible despues de restar fijos = " & invDispParaPromo, Colors.Blue) + + totalProdsVariablesDisponibles = 0 + For i = 0 To idProdsVariables.Size - 1 'Obtenemos total de productos variables disponibes. + If invDispParaPromo.ContainsKey(idProdsVariables.Get(i)) Then + totalProdsVariablesDisponibles = totalProdsVariablesDisponibles + invDispParaPromo.Get(idProdsVariables.Get(i)) + End If + Next + 'Revisamos variables. + If thisLog Then Log($"Var disponibles - var requeridos : ${totalProdsVariablesDisponibles} - ${prodsVariablesRequeridos*x}"$) + totalProdsVariablesDisponibles = totalProdsVariablesDisponibles - (prodsVariablesRequeridos*x) + If thisLog Then Log("prodsVariables disponibles despues de promo = " & totalProdsVariablesDisponibles) + If totalProdsVariablesDisponibles < 0 Then Exit 'Ya no hay inventario disponible. + maxPromosXVariables = x + Next + 'Restamos fijos. + LogColor("Max promos de prodsVariables POR inventario = " & maxPromosXVariables, Colors.red) + Return maxPromosXVariables +End Sub + +'Regresa la suma del inventario de los productos variables de la promoción dada desde la base de datos. +Sub cuantosVariablesTengoBD(promo As String) As String 'ignore +' Private x As String = "0" +' If promo <> "" Then +' Private c As Cursor +' c = Starter.skmt.ExecQuery2("Select SUM(CAT_GP_ALMACEN) as variables FROM CAT_GUNAPROD2 WHERE CAT_GP_ID IN (Select CAT_DP_IDPROD FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID = ? and cat_dp_tipo = 1 GROUP BY CAT_DP_IDPROD)", Array As String (promo)) +' If c.RowCount > -1 Then +' c.Position = 0 +' If c.GetString("variables") <> Null Then x = c.GetString("variables") +' End If +' End If +' Return x +End Sub + +'Regresa un mapa con los datos del producto desde la base de datos. +'el mapa incluye: Id, nombre, tipo y subtipo del producto. +Sub traeProdIdDeBD As Map 'ignore + Private c As Cursor + Private m As Map + c=B4XPages.MainPage.skmt.ExecQuery("select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_TIPO, CAT_GP_SUBTIPO from CAT_GUNAPROD where CAT_GP_NOMBRE In (Select PDESC from PROID)") + If c.RowCount > 0 Then + c.Position = 0 + m = CreateMap("id":c.GetString("CAT_GP_ID"), "nombre":c.GetString("CAT_GP_NOMBRE"), "tipo":c.GetString("CAT_GP_TIPO"), "subtipo":c.GetString("CAT_GP_SUBTIPO")) + Else + m = CreateMap("id":"N/A", "nombre":"N/A", "tipo":"N/A", "subtipo":"N/A") + End If + c.Close + Return m +End Sub + + +'Regresa un mapa con los datos del producto desde la base de datos. +'el mapa incluye: Id, nombre, tipo y subtipo del producto. +Sub traePromoIdDeBD As Map 'ignore + Private c As Cursor + Private m As Map + + Log("ENTRE") + c=B4XPages.MainPage.skmt.ExecQuery("select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_TIPO, CAT_GP_SUBTIPO from CAT_GUNAPROD where CAT_GP_NOMBRE In (Select PDESC from PROID) and CAT_GP_TIPO = 'PROMOS'") + If c.RowCount > 0 Then + c.Position = 0 + m = CreateMap("id":c.GetString("CAT_GP_ID"), "nombre":c.GetString("CAT_GP_NOMBRE"), "tipo":c.GetString("CAT_GP_TIPO"), "subtipo":c.GetString("CAT_GP_SUBTIPO")) + Else + m = CreateMap("id":"N/A", "nombre":"N/A", "tipo":"N/A", "subtipo":"N/A") + End If + c.Close + + Return m +End Sub + +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 = B4XPages.MainPage.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 + B4XPages.MainPage.skmt.ExecNonQuery($"ALTER TABLE ${tabla} ADD COLUMN ${columna} ${tipo}"$) +' Log($"Columna "${columna} ${tipo}", agregada a "${tabla}"."$) + End If +' Log(1) + Catch 'Si no funciona "pragma_table_info" lo hacemos con try/catch + Try + B4XPages.MainPage.skmt.ExecNonQuery($"ALTER TABLE ${tabla} ADD COLUMN ${columna} ${tipo}"$) + Log($"Columna "${columna} ${tipo}", agregada a "${tabla}".."$) + Catch + Log(LastException) + End Try + Log(2) + End Try +End Sub + +'Guarda el nombre y version de la app en CAT_VARIABLES. +Sub guardaAppInfo 'ignore + B4XPages.MainPage.skmt.ExecNonQuery("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'EMPRESA' or CAT_VA_DESCRIPCION = 'APP_NAME' or CAT_VA_DESCRIPCION = 'APP_VERSION'") + B4XPages.MainPage.skmt.ExecNonQuery($"insert into CAT_VARIABLES (CAT_VA_DESCRIPCION, CAT_VA_VALOR) values ('APP_NAME', '${Application.LabelName}')"$) + B4XPages.MainPage.skmt.ExecNonQuery($"insert into CAT_VARIABLES (CAT_VA_DESCRIPCION, CAT_VA_VALOR) values ('APP_VERSION', '${Application.VersionName}')"$) +End Sub + +Sub TraeMontoProd As Boolean + Private x As Boolean = False + Private c As Cursor = B4XPages.MainPage.skmt.ExecQuery("SELECT ifnull( SUM (PE_COSTO_TOT),0) As suma FROM PEDIDO JOIN CAT_PROMO_ESP ON CAT_PE_ID = PE_PROID WHERE PE_CLIENTE IN (Select CUENTA FROM CUENTAA)") + If c.RowCount > 0 Then + c.Position = 0 + Private c2 As Cursor = B4XPages.MainPage.skmt.ExecQuery("SELECT DISTINCT CAT_PE_MONTO FROM CAT_PROMO_ESP") + If c2.RowCount > 0 Then + c2.Position = 0 + + If c.GetString("suma") >= c2.GetString("CAT_PE_MONTO") Then + x = True + Log("verdadero") + Else + x = False + Log("Falso") + End If + + End If + End If + Return x +End Sub + +Sub InvSuficientePromoEsp As Boolean + Private y As Boolean = False + Private c As Cursor = B4XPages.MainPage.skmt.ExecQuery("select CAT_DP_IDPROD, CAT_DP_PZAS, ifnull(CAT_GP_ALMACEN, 0) As CAT_GP_ALMACEN from CAT_DETALLES_PAQ left JOIN CAT_GUNAPROD ON CAT_DP_IDPROD = CAT_GP_ID WHERE CAT_DP_ID IN (SELECT DISTINCT CAT_PE_IDPROMO FROM CAT_PROMO_ESP)") + If c.RowCount > 0 Then + For i = 0 To c.RowCount - 1 + c.Position = i + If c.GetString("CAT_GP_ALMACEN") >= c.GetString("CAT_DP_PZAS") Then + y = True +' Log("verdadero "& c.GetString("CAT_DP_IDPROD")) +' Log(c.GetString("CAT_GP_ALMACEN") &" "& c.GetString("CAT_DP_PZAS")) + Else + y = False +' Log("falso "& c.GetString("CAT_DP_IDPROD")) +' Log(c.GetString("CAT_GP_ALMACEN") &" "& c.GetString("CAT_DP_PZAS")) + Exit + End If + Next + End If + c.Close + Return y +End Sub + +Sub vendidoPromoEsp As Boolean + Private w As Boolean = False + Private c As Cursor = B4XPages.MainPage.skmt.ExecQuery("select HP_CLIENTE, HP_CODIGO_PROMOCION from HIST_PROMOS WHERE HP_CODIGO_PROMOCION IN (SELECT DISTINCT CAT_PE_IDPROMO FROM CAT_PROMO_ESP) AND HP_CLIENTE IN (SELECT CUENTA FROM CUENTAA)") + If c.RowCount > 0 Then + w = True + End If + Log(w) + c.Close + Private c As Cursor = B4XPages.MainPage.skmt.ExecQuery("select PE_PROID from PEDIDO WHERE PE_PROID IN (SELECT DISTINCT CAT_PE_IDPROMO FROM CAT_PROMO_ESP) AND PE_CLIENTE IN (SELECT CUENTA FROM CUENTAA)") + If c.RowCount > 0 Then + w = True + End If + c.Close + Log(w) + Return w +End Sub + + +'En geocerca si mete la contraseña poner 0 en precision gps y si esta dentro de los 50 mts poner 1 y 2 para eventos que no lo ocupen +'Mandar fecha de sync(sysdate) +Sub bitacora(fechab As String, usuariob As String, almacenb As String, rutab As String, eventob As String, clienteb As String, iniciob As String, finb As String, latitudb As String, longitudb As String, precision As String, motivonoventa As String, motivonovisita As String ) + Log(motivonovisita) + Log("bitacora") + Private cmd As DBCommand + cmd.Initialize + cmd.Name = "mandaBitacora3" + Log("BITACORA3") + Private nombreCliente As String = traeNombreCliente(clienteb) + If eventob = "Llega a almacen" Then + nombreCliente = "BOLETA" + clienteb = "" + finb = iniciob + End If + If eventob = "Salida almacen" Then nombreCliente = "CHECKLIST" + If eventob = "Fin Día" Then nombreCliente = "FIN DIA" + If eventob = "Carga día" Then nombreCliente = "CARGA DIA" + If eventob <> "Termina Venta" And eventob <> "No Venta" Then + B4XPages.MainPage.skmt.ExecNonQuery($"INSERT INTO BITACORAGPS (fechab, usuariob , almacenb , rutab , eventob , clienteb , iniciob , finb , latitudb, longitudb , precision , motivonoventa , motivonovisita) VALUES ('${fechab}' ,'${usuariob}' , '${almacenb}' , '${rutab}' , '${eventob}' , '${clienteb}' , '${iniciob}' , '${finb}' , '${latitudb}' , '${longitudb}' , '${precision}' , '${motivonoventa}' , '${motivonovisita}')"$) + Log($"'${almacenb}', '${usuariob}', '${rutab}', '${eventob}', '${clienteb}', '${nombreCliente}','${ iniciob}', '${finb}','${ latitudb}','${ longitudb}', '${precision}', '${motivonoventa}', '${motivonovisita}', '${fechab}'"$) +' TMP_ALMACEN, TMP_USUARIO, TMP_RUTA, TMP_EVENTO, TMP_ID_CLIENTE, TMP_NOMBRE_CLIENTE, TMP_INICIO, TMP_FINAL, TMP_LATITUD, TMP_LONGITUD, TMP_PRESICION, TMP_MOTIVO_NO_VENTA, TMP_MOTIVO_NO_VISITA, TMP_FECHA_SINC, TMP_FECHA_MOVIL +' cmd.Parameters = Array As Object(almacenb, usuariob, rutab, eventob, clienteb, nombreCliente, iniciob, finb, latitudb, longitudb, precision, motivonoventa, motivonovisita, fechab) +' Starter.reqManager.ExecuteCommand(cmd , "mandaBitacora") + Else + Private e As Cursor = B4XPages.MainPage.skmt.ExecQuery($"select fechab from BITACORAGPS where usuariob = '${usuariob}' and almacenb = '${almacenb}' and rutab = '${rutab}' and clienteb = '${clienteb}' and eventob = 'Inicia Venta' order by fechab desc"$) +' TMP_RUTA = (?) And tmp_almacen = (?) And tmp_usuario = (?) And tmp_id_cliente = (?) And tmp_evento = (?) And tmp_fecha_movil = to_date((?),'YYYY/MM/DD HH24:MI:ss') + If e.RowCount > 0 Then + e.Position = 0 + Log("ACTUALIZA BITACORA") + If eventob = "Termina Venta" Then + B4XPages.MainPage.skmt.ExecNonQuery($"update BITACORAGPS set finb = '${finb}' where rutab = '${rutab}' and almacenb = '${almacenb}' and usuariob = '${usuariob}' and clienteb = '${clienteb}' and fechab = '${e.GetString("fechab")}' "$) +' cmd.Name = "actualizaSalidaBitacora" +' TMP_FINAL = to_date((?),'YYYY/MM/DD HH24:MI:ss') where TMP_RUTA = (?) and tmp_almacen = (?) and tmp_usuario = (?) and tmp_id_cliente = (?) and tmp_evento = (?) and tmp_fecha_movil = to_date((?),'YYYY/MM/DD HH24:MI:ss'); + cmd.Parameters = Array As Object(finb, rutab, almacenb, usuariob, clienteb, "Inicia Venta", e.GetString("fechab")) +' Log($"${finb}, ${rutab}, ${almacenb}, ${usuariob}, ${clienteb}, 'Inicia Venta', ${e.GetString("fechab")}, "$) +' Starter.reqManager.ExecuteCommand(cmd , "mandaBitacora") + else if eventob = "No Venta" Then + B4XPages.MainPage.skmt.ExecNonQuery($"update BITACORAGPS set finb = '${finb}', motivonoventa = '${motivonoventa}', motivonovisita = '${motivonovisita}' where rutab = '${rutab}' and almacenb = '${almacenb}' and usuariob = '${usuariob}' and clienteb = '${clienteb}' and fechab = '${e.GetString("fechab")}' "$) +' cmd.Name = "actualizaNoVentaBitacora" +' TMP_FINAL = to_date((?),'YYYY/MM/DD HH24:MI:ss'), TMP_MOTIVO_NO_VENTA = (?), TMP_MOTIVO_NO_VISITA = (?) where TMP_RUTA = (?) and tmp_almacen = (?) and tmp_usuario = (?) and tmp_id_cliente = (?) and tmp_evento = (?) and tmp_fecha_movil = to_date((?),'YYYY/MM/DD HH24:MI:ss') + cmd.Parameters = Array As Object(finb, motivonoventa, motivonovisita, rutab, almacenb, usuariob, clienteb, "Inicia Venta", e.GetString("fechab")) +' Log($"${finb}, ${rutab}, ${almacenb}, ${usuariob}, ${clienteb}, 'Inicia Venta', ${e.GetString("fechab")}, "$) +' Starter.reqManager.ExecuteCommand(cmd , "mandaBitacora") + End If + End If + End If + If eventob <> "Inicia Venta" Then + Private c As Cursor = B4XPages.MainPage.skmt.ExecQuery($"select * from BITACORAGPS where usuariob = '${usuariob}' and almacenb = '${almacenb}' and rutab = '${rutab}' and clienteb = '${clienteb}' order by fechab desc"$) + If c.RowCount > 0 Then + c.Position = 0 + cmd.Parameters = Array As Object(c.GetString("almacenb"), c.GetString("usuariob"), c.GetString("rutab"), c.GetString("eventob"), c.GetString("clienteb"), nombreCliente, c.GetString("iniciob"), c.GetString("finb"), c.GetString("latitudb"), c.GetString("longitudb"), c.GetString("precision"), c.GetString("motivonoventa"), c.GetString("motivonovisita"), c.GetString("fechab")) +' Starter.reqManager.ExecuteCommand(cmd , "mandaBitacora") + End If + End If + Log("Mandamos bitacora") +End Sub + +'En geocerca si mete la contraseña poner 0 en precision gps y si esta dentro de los 50 mts poner 1 y 2 para eventos que no lo ocupen +'Mandar fecha de sync(sysdate) +Sub bitacoraX(fechab As String, usuariob As String, almacenb As String, rutab As String, eventob As String, clienteb As String, iniciob As String, finb As String, latitudb As String, longitudb As String, precision As String, motivonoventa As String, motivonovisita As String ) + Log("bitacora") + B4XPages.MainPage.skmt.ExecNonQuery($"INSERT INTO BITACORAGPS (fechab, usuariob , almacenb , rutab , eventob , clienteb , iniciob , finb , latitudb, longitudb , precision , motivonoventa , motivonovisita) VALUES ('${fechab}' ,'${usuariob}' , '${almacenb}' , '${rutab}' , '${eventob}' , '${clienteb}' , '${iniciob}' , '${finb}' , '${latitudb}' , '${longitudb}' , '${precision}' , '${motivonoventa}' , '${motivonovisita}')"$) + Private cmd As DBCommand + cmd.Initialize + If eventob <> "Termina Venta" And eventob <> "No Venta" Then + cmd.Name = "mandaBitacora3" + Log("BITACORA3") + Private nombreCliente As String = traeNombreCliente(clienteb) + If eventob = "Llega a almacen" Then + nombreCliente = "BOLETA" + clienteb = "" + finb = iniciob + End If + If eventob = "Salida almacen" Then nombreCliente = "CHECKLIST" + If eventob = "Fin Día" Then nombreCliente = "FIN DIA" + If eventob = "Carga día" Then nombreCliente = "CARGA DIA" + Log($"'${almacenb}', '${usuariob}', '${rutab}', '${eventob}', '${clienteb}', '${nombreCliente}','${ iniciob}', '${finb}','${ latitudb}','${ longitudb}', '${precision}', '${motivonoventa}', '${motivonovisita}', '${fechab}'"$) +' TMP_ALMACEN, TMP_USUARIO, TMP_RUTA, TMP_EVENTO, TMP_ID_CLIENTE, TMP_NOMBRE_CLIENTE, TMP_INICIO, TMP_FINAL, TMP_LATITUD, TMP_LONGITUD, TMP_PRESICION, TMP_MOTIVO_NO_VENTA, TMP_MOTIVO_NO_VISITA, TMP_FECHA_SINC, TMP_FECHA_MOVIL + cmd.Parameters = Array As Object(almacenb, usuariob, rutab, eventob, clienteb, nombreCliente, iniciob, finb, latitudb, longitudb, precision, motivonoventa, motivonovisita, fechab) +' Starter.reqManager.ExecuteCommand(cmd , "mandaBitacora") + Else + Private e As Cursor = B4XPages.MainPage.skmt.ExecQuery($"select fechab from BITACORAGPS where usuariob = '${usuariob}' and almacenb = '${almacenb}' and rutab = '${rutab}' and clienteb = '${clienteb}' and eventob = 'Inicia Venta' order by fechab desc"$) + If e.RowCount > 0 Then + e.Position = 0 + Log("ACTUALIZA BITACORA") + If eventob = "Termina Venta" Then + cmd.Name = "actualizaSalidaBitacora" +' TMP_FINAL = to_date((?),'YYYY/MM/DD HH24:MI:ss') where TMP_RUTA = (?) and tmp_almacen = (?) and tmp_usuario = (?) and tmp_id_cliente = (?) and tmp_evento = (?) and tmp_fecha_movil = to_date((?),'YYYY/MM/DD HH24:MI:ss'); + cmd.Parameters = Array As Object(finb, rutab, almacenb, usuariob, clienteb, "Inicia Venta", e.GetString("fechab")) + Log($"${finb}, ${rutab}, ${almacenb}, ${usuariob}, ${clienteb}, 'Inicia Venta', ${e.GetString("fechab")}, "$) +' Starter.reqManager.ExecuteCommand(cmd , "mandaBitacora") + else if eventob = "No Venta" Then + cmd.Name = "actualizaNoVentaBitacora" +' TMP_FINAL = to_date((?),'YYYY/MM/DD HH24:MI:ss') where TMP_RUTA = (?) and tmp_almacen = (?) and tmp_usuario = (?) and tmp_id_cliente = (?) and tmp_evento = (?) and tmp_fecha_movil = to_date((?),'YYYY/MM/DD HH24:MI:ss'); + cmd.Parameters = Array As Object(finb, motivonoventa, motivonovisita, rutab, almacenb, usuariob, clienteb, "Inicia Venta", e.GetString("fechab")) + Log($"${finb}, ${rutab}, ${almacenb}, ${usuariob}, ${clienteb}, 'Inicia Venta', ${e.GetString("fechab")}, "$) +' Starter.reqManager.ExecuteCommand(cmd , "mandaBitacora") + End If + End If + End If + Log("Mandamos bitacora") +End Sub + +'Regresa el nombre del cliente del id dado. +Sub traeNombreCliente(id As String) As String + Private c As ResultSet = B4XPages.MainPage.skmt.ExecQuery($"select CAT_CL_NOMBRE from kmt_info2 where CAT_CL_CODIGO = '${id}'"$) + Private n As String = "N/A" + Do While c.NextRow + n = c.GetString("CAT_CL_NOMBRE") + Loop + Return n +End Sub + +'Guarda el nombre de la pagina en base de datos la muestra. +Sub iniciaActividad(ia As String) + If ia <> "" And ia <> Null Then +' If B4XPages.MainPage.logger Then LogColor($"Guardamos en BD '${ia}'"$, Colors.Yellow) + B4XPages.MainPage.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("ULTIMOMODULO")) + B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("ULTIMOMODULO", ia)) + B4XPages.ShowPage(ia) +' If B4XPages.MainPage.logger Then LogColor("Iniciamos --> " & ia, Colors.Blue) + End If +End Sub diff --git a/B4XMainPage.bas b/B4XMainPage.bas new file mode 100644 index 0000000..bade5c2 --- /dev/null +++ b/B4XMainPage.bas @@ -0,0 +1,697 @@ +B4A=true +Group=Default Group +ModulesStructureVersion=1 +Type=Class +Version=9.85 +@EndOfDesignText@ +#Region Shared Files +'#CustomBuildAction: folders ready, %WINDIR%\System32\Robocopy.exe,"..\..\Shared Files" "..\Files" + 'Ctrl + click to sync files: ide://run?file=%WINDIR%\System32\Robocopy.exe&args=..\..\Shared+Files&args=..\Files&FilesSync=True + 'Ctrl + click to export as zip: ide://run?File=%B4X%\Zipper.jar&Args=Project.zip + '########################################################################################################### + '###################### 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 + +'Ctrl + click to export as zip: ide://run?File=%B4X%\Zipper.jar&Args=Project.zip + +Sub Class_Globals + Private b_salida As Button + Private b_entrada As Button + Private b_cancelar As Button + Private b_guardar As Button + Private b_regresar As Button + Dim c As Cursor + Dim t As Cursor + Dim cmd As DBCommand + Private et_placa As EditText + Private Root As B4XView + Dim RES As String + Dim RES3 As String + Dim RES5 As String + Private p_estacionamiento As Panel + Private p_guarda_info As Panel + Private p_sal_esta As Panel + Public Provider As FileProvider +' Private xui As XUI + Dim skmt As SQL + Private lv_Lis_Placa As ListView + Dim TAMANO As Int + Dim ESPACIO As Int + Dim BLANCO As String + Dim printer As TextWriter + Dim cmp20 As Serial + Dim btAdmin As BluetoothAdmin + Dim Printer1 As EscPosPrinter + Dim impresoraConectada As Boolean = False + Dim errorImpresora As Int = 0 + Dim p As Int + Dim v As Object + Private LogoEst As ImageView + Private LogEst_lv As ImageView + Private LogoEst_placa As ImageView + Private b_Tarifa As Button + Private p_tar_f As Panel + Private et_tar_f As EditText + Private b_tar_can As Button + Private b_tar_in As Button + Private b_resdia As Button + Private LogEst_res As ImageView + Private p_res As Panel + Private l_totales As Label + Private l_totalsal As Label + Private l_montoto As Label + Private b_resacep As Button + Private b_rescan As Button +End Sub + +Public Sub Initialize +' B4XPages.GetManager.LogEvents = True +End Sub + +'This event will be called once, before the page becomes visible. +Private Sub B4XPage_Created (Root1 As B4XView) + Provider.Initialize + skmt.Initialize(File.DirInternal,"kmt.db", True) + Root = Root1 + Root.LoadLayout("MainPage") + skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_VARIABLES (CAT_VA_DESCRIPCION TEXT, CAT_VA_VALOR TEXT)") + skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS TMP_INFO_EnSal (TMP_PLACA TEXT, TMP_HR_ENTRA TEXT, TMP_HR_SAL TEXT)") + skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS TMP_TARIFA (TMP_TAR_H TEXT)") + skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_PLACAS (PLACA TEXT, ENTRADA TEXT, SALIDA TEXT, MONTO TEXT, FOLIO TEXT)") + Subs.agregaColumna("TMP_INFO_EnSal", "TMP_DEN_FUE", "INTEGER") + Subs.agregaColumna("TMP_INFO_EnSal", "TMP_FOLIO", "TEXT") + + + AjustarInterfaz(Root.Width, Root.Height) + + btAdmin.Initialize("BlueTeeth") + cmp20.Initialize("Printer") + +End Sub + +Private Sub AjustarInterfaz(Ancho As Int, Alto As Int) + + p_estacionamiento.SetLayoutAnimated(0, 0, 0, Ancho, Alto) + p_guarda_info.SetLayoutAnimated(0, 0, 0, Ancho, Alto) + p_sal_esta.SetLayoutAnimated(0, 0, 0, Ancho, Alto) + p_res.SetLayoutAnimated(0, 0, 0, Ancho, Alto) + + + Dim margenVertical As Int = Alto * 0.02 + Dim margenHorizontal As Int = Ancho * 0.05 + Dim botonAncho As Int = (Ancho - (margenHorizontal * 4)) / 3 + Dim botonAlto As Int = Alto * 0.09 + Dim botonesY As Int = Alto - botonAlto - margenVertical + Dim espacioEntreBotones As Int = margenVertical + + Dim bAncho As Int = (Ancho - (margenHorizontal * 4)) + + Dim centroX As Int = (Ancho - bAncho) / 2 + Dim centroY As Int = (Alto - (3 * botonAlto + 2 * espacioEntreBotones)) / 2 + + b_entrada.SetLayoutAnimated(0, centroX, centroY, bAncho, botonAlto) + b_salida.SetLayoutAnimated(0, centroX, b_entrada.Top + botonAlto + espacioEntreBotones, bAncho, botonAlto) + b_Tarifa.SetLayoutAnimated(0,centroX, b_salida.Top + botonAlto + espacioEntreBotones, bAncho, botonAlto) + b_resdia.SetLayoutAnimated(0,centroX, b_Tarifa.Top + botonAlto + espacioEntreBotones, bAncho, botonAlto) + + b_guardar.SetLayoutAnimated(0, margenHorizontal, botonesY, botonAncho, botonAlto) + b_cancelar.SetLayoutAnimated(0, margenHorizontal + 2 * (botonAncho + margenHorizontal), botonesY, botonAncho, botonAlto) + b_regresar.SetLayoutAnimated(0, margenHorizontal + 1 * (botonAncho + margenHorizontal), botonesY, botonAncho, botonAlto) + b_rescan.SetLayoutAnimated(0, margenHorizontal + 1 * (botonAncho + margenHorizontal), botonesY, botonAncho, botonAlto) + b_resacep.SetLayoutAnimated(0, margenHorizontal + 1 * (botonAncho + margenHorizontal), botonesY, botonAncho, botonAlto) + + + Dim logoAncho As Int = Ancho * 0.3 + Dim logoAlto As Int = Alto * 0.2 + Dim logoY As Int = margenVertical + + LogoEst.SetLayoutAnimated(0, margenHorizontal, logoY, logoAncho, logoAlto) + LogEst_lv.SetLayoutAnimated(0, margenHorizontal, logoY, logoAncho, logoAlto) + LogoEst_placa.SetLayoutAnimated(0, margenHorizontal, logoY, logoAncho, logoAlto) + LogEst_res.SetLayoutAnimated(0, margenHorizontal, logoY, logoAncho, logoAlto) + + lv_Lis_Placa.SetLayoutAnimated(0, margenHorizontal, logoY + logoAlto + margenVertical, Ancho - 2 * margenHorizontal, b_regresar.Top - logoAlto - 2 * margenVertical) + + p_guarda_info.BringToFront +End Sub + + +Private Sub B4XPage_Resize(Width As Int, Height As Int) + AjustarInterfaz(Width, Height) +End Sub + +Private Sub b_entrada_Click + + Dim t As Cursor = skmt.ExecQuery("SELECT TMP_TAR_H FROM TMP_TARIFA") + If t.RowCount > 0 Then + t.Position = 0 + Log(t.GetString("TMP_TAR_H")) + + et_placa.Text = "" + + b_entrada.Visible = False + b_salida.Visible = False + p_guarda_info.Visible = True + p_estacionamiento.Visible = False + et_placa.Visible = True + p_guarda_info.BringToFront + + Else If t.RowCount = 0 Then + + MsgboxAsync("Favor de caprurar la tarifa por hora", "Atención") + + End If + + +End Sub + +Private Sub b_salida_Click + lv_Lis_Placa.Clear + b_entrada.Visible = False + b_salida.Visible = False + p_guarda_info.Visible = False + p_estacionamiento.Visible = False + p_sal_esta.Visible = True + lv_Lis_Placa.Visible = True + lv_Lis_Placa.BringToFront + + Private l1 As Label = lv_Lis_Placa.SingleLineLayout.Label + l1.TextColor = Colors.Black + + c = skmt.ExecQuery("SELECT TMP_PLACA, TMP_HR_ENTRA, TMP_HR_SAL, TMP_DEN_FUE FROM TMP_INFO_EnSal") + + If c.RowCount > 0 Then + + lv_Lis_Placa.Clear + For i = 0 To c.RowCount - 1 + c.Position = i + If c.GetString("TMP_DEN_FUE") <> 1 Then + lv_Lis_Placa.AddSingleLine(c.GetString("TMP_PLACA")) + End If + Next + End If + c.Close +End Sub + +Private Sub b_salida_LongClick + RES = Msgbox2("Seguro que desea hacer el cierre todos los datos se borraran?","Cierre", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png")) 'ignore + If RES = DialogResponse.POSITIVE Then + skmt.ExecNonQuery("DELETE FROM TMP_INFO_EnSal") + skmt.ExecNonQuery("DELETE FROM HIST_PLACAS") + skmt.ExecNonQuery("DELETE FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = 'Folio'") + End If +End Sub + +Private Sub lv_Lis_Placa_ItemClick (Position As Int, Value As Object) + RES = Msgbox2Async("¿Seguro que esta placa va a salir?", "Cierre", "Sí", "", "No", LoadBitmap(File.DirAssets, "alert2.png"), False) + Wait For Msgbox_Result(RES2 As Int) + If RES2 = DialogResponse.POSITIVE Then + + v = Value + p = Position + Impresion + + End If +End Sub + +Sub Impresion + Dim placaSeleccionada As String = v + c = skmt.ExecQuery2("SELECT TMP_PLACA, TMP_HR_ENTRA, TMP_HR_SAL, TMP_DEN_FUE, TMP_FOLIO FROM TMP_INFO_EnSal WHERE TMP_PLACA = ?", Array As String(placaSeleccionada)) + + If c.RowCount > 0 Then + c.Position = 0 + + Dim fechaSalida As String = Subs.traeFecha + Dim fechaEntrada As String = c.GetString("TMP_HR_ENTRA") + Dim partesFechaEntrada() As String = Regex.Split(" ", fechaEntrada) + Dim partesFechaSalida() As String = Regex.Split(" ", fechaSalida) + + If partesFechaEntrada.Length > 1 And partesFechaSalida.Length > 1 Then + + Dim fechaSalida As String = Subs.traeFecha + Dim fechaEntrada As String = c.GetString("TMP_HR_ENTRA") + + Dim partesFechaEntrada() As String = Regex.Split(" ", fechaEntrada) + Dim partesFechaSalida() As String = Regex.Split(" ", fechaSalida) + + If partesFechaEntrada.Length > 1 And partesFechaSalida.Length > 1 Then + Dim horaEntrada As String = partesFechaEntrada(1) + Dim fechaEntrada As String = partesFechaEntrada(0) + + Dim horaSalida As String = partesFechaSalida(1) + Dim fechaSalida As String = partesFechaSalida(0) + + Dim milisEntrada As Long = DateTime.TimeParse(horaEntrada) + Dim milisSalida As Long = DateTime.TimeParse(horaSalida) + + Dim diasEntrada As Long = DateTime.DateParse(fechaEntrada) / DateTime.TicksPerDay + Dim diasSalida As Long = DateTime.DateParse(fechaSalida) / DateTime.TicksPerDay + + Dim diferenciaDiasEnMilis As Long = (diasSalida - diasEntrada) * DateTime.TicksPerDay + Dim diferenciaTotalMilis As Long = (milisSalida + diferenciaDiasEnMilis) - milisEntrada + + Dim diferenciaTotalSegundos As Long = diferenciaTotalMilis / DateTime.TicksPerSecond + Dim diferenciaTotalMinutos As Long = diferenciaTotalSegundos / 60 + Dim diferenciaTotalHoras As Long = diferenciaTotalMinutos / 60 + + Dim horasRestantes As Long = diferenciaTotalHoras + Dim minutosRestantes As Long = diferenciaTotalMinutos Mod 60 + Dim segundosRestantes As Long = diferenciaTotalSegundos Mod 60 + + Log("Horas restantes: " & horasRestantes) + Log("Minutos restantes: " & minutosRestantes) + Log("Segundos restantes: " & segundosRestantes) + End If + + +' printer.WriteLine("------------------------------") +' printer.WriteLine("---NO ES UN COMPROBANTE ------") +' printer.WriteLine("---------FISCAL---------------") +' printer.WriteLine("---COMPROBANTE DE ENTREGA-----") +' printer.WriteLine("------------------------------") + + Else + Log("Formato de fecha incorrecto en entrada o salida.") + End If + + + ProgressDialogShow("Imprimiendo, un momento ...") + Printer1.DisConnect + If Not(Printer1.IsConnected) Then + Log("Conectando a impresora ...") + Printer1.Connect + Private cont As Int = 0 + Do While Not(impresoraConectada) + Sleep(1000) + Log("++++++ " & cont) + cont = cont + 1 + If cont = 2 Then Printer1.Connect 'Tratamos de reconectar + If cont > 3 Then impresoraConectada = True + Loop + Sleep(500) + impresoraConectada = False + Else + Log("conectando 2") + Printer1.Connect + Private cont As Int = 0 + Do While Not(impresoraConectada) Or Not(Printer1.IsConnected) + Sleep(1000) + Log("****** " & cont) + cont = cont + 1 + If cont = 2 Then Printer1.Connect + If cont > 3 Then impresoraConectada = True + Loop + Sleep(500) + impresoraConectada = False + End If + t = skmt.ExecQuery("SELECT TMP_TAR_H FROM TMP_TARIFA") + If t.RowCount > 0 Then + t.Position = 0 + Log(t.GetString("TMP_TAR_H")) + + + Private sDate As String =DateTime.Date(DateTime.Now) + Private sTime As String =DateTime.Time(DateTime.Now) + + Printer1.WriteString(" " & CRLF) + Printer1.WriteString(" " & CRLF) + + Printer1.WriteString(" Establecimietno: " & CRLF) + Printer1.WriteString(" La Antigua, Restaurante - Bar" & CRLF) + Printer1.WriteString(" Fecha: " & sDate & " " & sTime & " " & CRLF) + Printer1.WriteString(" Folio: " & c.GetString("TMP_FOLIO") & CRLF) + Printer1.WriteString(Chr(27) & Chr(69)) ' Código ESC/P para iniciar negritas + Printer1.WriteString(" Placa: " & c.GetString("TMP_PLACA") & " " & CRLF) + Printer1.WriteString(Chr(27) & Chr(70)) ' Código ESC/P para finalizar negritas + Printer1.WriteString("Hora Entrada:" & c.GetString("TMP_HR_ENTRA")& CRLF) + Printer1.WriteString("Hora Salida: " & Subs.traeFecha& CRLF) + Printer1.WriteString("Tarifa por Hora: " & t.GetString("TMP_TAR_H") & CRLF) + Printer1.WriteString("Horas: " & horasRestantes & CRLF) + Printer1.WriteString("Munutos: " & minutosRestantes & CRLF) + Printer1.WriteString("Total a pagar: " & Subs.CalcularCosto(diferenciaTotalMinutos, t.GetString("TMP_TAR_H"))& CRLF) + + Printer1.WriteString(" " & CRLF) + Printer1.WriteString(" " & CRLF) + Printer1.WriteString(" " & CRLF) + Printer1.WriteString(" " & CRLF) + Sleep(1000) + Printer1.DisConnect + + ProgressDialogHide + + RES3 = Msgbox2Async("¿Deceas volver a imprimir el ticket?", "Cierre", "Sí", "", "No", LoadBitmap(File.DirAssets, "alert2.png"), False) + Wait For Msgbox_Result(RES4 As Int) + + If RES4 = DialogResponse.POSITIVE Then + Impresion + Else + skmt.ExecNonQuery2("INSERT INTO HIST_PLACAS(PLACA, ENTRADA, SALIDA, MONTO, FOLIO) values(?,?,?,?,?)", Array As String(c.GetString("TMP_PLACA"),c.GetString("TMP_HR_ENTRA"),Subs.traeFecha,Subs.CalcularCosto(diferenciaTotalMinutos, t.GetString("TMP_TAR_H")),c.GetString("TMP_FOLIO"))) + p_estacionamiento.Visible = True + b_entrada.Visible = True + b_salida.Visible = True + lv_Lis_Placa.Visible = False + p_sal_esta.Visible = False + skmt.ExecNonQuery2("DELETE FROM TMP_INFO_EnSal WHERE TMP_PLACA = ? and TMP_FOLIO = ? ", Array As String(c.GetString("TMP_PLACA"), c.GetString("TMP_FOLIO"))) + End If + + End If + t.Close + c.Close + End If +End Sub + + + + +Private Sub b_regresar_Click + p_estacionamiento.Visible = True + b_entrada.Visible = True + b_salida.Visible = True + lv_Lis_Placa.Visible = False + p_sal_esta.Visible = False +End Sub + +Private Sub b_guardar_Click + 'Verificamos que haya una placa escrita + If et_placa.Text <> "" Then + + 'Verificamos que haya un folio o no + Private check As Cursor = skmt.ExecQuery($"SELECT * FROM TMP_INFO_EnSal WHERE TMP_PLACA = '${et_placa.Text}'"$) + If check.RowCount = 0 Then + + Private folio As Cursor = skmt.ExecQuery($"SELECT * FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = 'Folio'"$) + If folio.RowCount = 0 Then + + skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) values(?,?)", Array As String("Folio", "1")) + + Private folioasing As Cursor = skmt.ExecQuery($"SELECT * FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = 'Folio'"$) + folioasing.Position = 0 + + skmt.ExecNonQuery2("INSERT INTO TMP_INFO_EnSal(TMP_PLACA, TMP_HR_ENTRA ,TMP_DEN_FUE ,TMP_FOLIO) values (?,?,?,?)", Array As String(et_placa.Text,Subs.traeFecha,0, folioasing.GetString("CAT_VA_VALOR"))) + + 'Vamos a llamar la rutina de impresion + imprime_Guarda + + folioasing.Close + + Else If folio.RowCount > 0 Then + + skmt.ExecNonQuery($"UPDATE CAT_VARIABLES SET CAT_VA_VALOR = CAT_VA_VALOR + 1 WHERE CAT_VA_DESCRIPCION = 'Folio' "$) + + Private folioasing As Cursor = skmt.ExecQuery($"SELECT * FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = 'Folio'"$) + folioasing.Position = 0 + + skmt.ExecNonQuery2("INSERT INTO TMP_INFO_EnSal(TMP_PLACA, TMP_HR_ENTRA ,TMP_DEN_FUE ,TMP_FOLIO) values (?,?,?,?)", Array As String(et_placa.Text,Subs.traeFecha,0, folioasing.GetString("CAT_VA_VALOR"))) + + 'Vamos a llamar la rutina de impresion + imprime_Guarda + + folioasing.Close + + End If + + Else If check.RowCount > 0 Then + + MsgboxAsync("El vehiculo esta en el estacionamiento","Atención") + + End If + + Else + + MsgboxAsync("Ingrese una placa valida","Atención") + + End If + + +End Sub + +Sub imprime_Guarda + + Private check As Cursor = skmt.ExecQuery($"SELECT * FROM TMP_INFO_EnSal WHERE TMP_PLACA = '${et_placa.Text}'"$) + If check.RowCount > 0 Then + + check.Position = 0 + + ProgressDialogShow("Imprimiendo, un momento ...") + Printer1.DisConnect + If Not(Printer1.IsConnected) Then + Log("Conectando a impresora ...") + Printer1.Connect + Private cont As Int = 0 + Do While Not(impresoraConectada) + Sleep(1000) + Log("++++++ " & cont) + cont = cont + 1 + If cont = 2 Then Printer1.Connect 'Tratamos de reconectar + If cont > 3 Then impresoraConectada = True + Loop + Sleep(500) + impresoraConectada = False + Else + Log("conectando 2") + Printer1.Connect + Private cont As Int = 0 + Do While Not(impresoraConectada) Or Not(Printer1.IsConnected) + Sleep(1000) + Log("****** " & cont) + cont = cont + 1 + If cont = 2 Then Printer1.Connect + If cont > 3 Then impresoraConectada = True + Loop + Sleep(500) + impresoraConectada = False + End If + + Private t As Cursor = skmt.ExecQuery("SELECT TMP_TAR_H FROM TMP_TARIFA") + t.Position = 0 + Dim folio As Cursor = skmt.ExecQuery($"SELECT * FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = 'Folio'"$) + folio.Position = 0 + + Dim fecha As String = check.GetString("TMP_HR_ENTRA") + Dim fechaHora() As String = Regex.Split(" ", fecha) + + + Printer1.WriteString(" " & CRLF) + Printer1.WriteString(" " & CRLF) + + Printer1.WriteString("Establecimietno:" & CRLF) + Printer1.WriteString("La Antigua, Restaurante - Bar" & CRLF) + Printer1.WriteString("Fecha: " & fechaHora(0) & CRLF) + Printer1.WriteString("Folio: " & folio.GetString("CAT_VA_VALOR")& CRLF) + Printer1.WriteString("Placa: " & et_placa.Text & CRLF) + Printer1.WriteString("Hora Entrada:" & fechaHora(1)& CRLF) + Printer1.WriteString("Tarifa por Hora: " & t.GetString("TMP_TAR_H") & CRLF) + + Printer1.WriteString(" " & CRLF) + Printer1.WriteString(" " & CRLF) + Sleep(1000) + Printer1.DisConnect + ProgressDialogHide + + folio.Close + t.Close + check.Close + + RES5 = Msgbox2Async("Deseas imprimirlo de nuevo?", "Atencion", "Sí", "", "No", LoadBitmap(File.DirAssets, "alert2.png"), False) + Wait For Msgbox_Result(RES6 As Int) + + If RES6 = DialogResponse.POSITIVE Then + imprime_Guarda + Else + MsgboxAsync("Datos Guardados", "AVISO") + p_guarda_info.Visible = False + p_estacionamiento.Visible = True + b_entrada.Visible = True + b_salida.Visible = True + b_Tarifa.Visible = True + End If + + End If + +End Sub + +Private Sub b_cancelar_Click + b_entrada.Visible = True + b_salida.Visible = True + p_guarda_info.Visible = False + p_estacionamiento.Visible = True + et_placa.Text = "" +End Sub + +Sub Printer_Connected (Success As Boolean) + If Success Then +' B_IMP.Enabled = True + StartPrinter + Else +' B_IMP.Enabled = False + If Msgbox2("", "Printer Error","Reprint","Cancel","",Null) = DialogResponse.POSITIVE Then 'Ignore + StartPrinter + End If + End If +End Sub + +Sub StartPrinter + Dim PairedDevices As Map + Dim L As List + Dim resimp As Int + ToastMessageShow("Printing.....",True) + PairedDevices.Initialize + Try + PairedDevices = cmp20.GetPairedDevices + Catch + Msgbox("Getting Paired Devices","Printer Error") 'Ignore + printer.Close + cmp20.Disconnect + End Try + If PairedDevices.Size = 0 Then + Msgbox("Error Connecting to Printer - Printer Not Found","") 'Ignore + Return + End If + If PairedDevices.Size = 1 Then + Try + cmp20.ConnectInsecure(btAdmin,PairedDevices.Get(PairedDevices.GetKeyAt(0)),1) + Catch + Msgbox("Connecting","Printer Error") 'Ignore + printer.Close + cmp20.Disconnect + End Try + Else + L.Initialize + For i = 0 To PairedDevices.Size - 1 + L.Add(PairedDevices.GetKeyAt(i)) + Next + resimp = InputList(L, "Choose device", -1) 'Ignore + If resimp <> DialogResponse.CANCEL Then + cmp20.Connect(PairedDevices.Get(L.Get(resimp))) + End If + End If +End Sub + + +Sub B4XPage_Appear + c = skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("MACIMP")) + If c.RowCount > 0 Then + c.Position = 0 + Starter.MAC_IMPRESORA = c.GetString("CAT_VA_VALOR") + End If + If Starter.MAC_IMPRESORA = "" Then Starter.MAC_IMPRESORA = "0" +' Log("|" & Starter.MAC_IMPRESORA & "|") + Printer1.Initialize(Me, "Printer1") + + If Printer1.IsConnected = False Then +' Printer1.Connect +' Log("1") + Else + Printer1.DisConnect + Printer1.Connect + Log("2") + End If +End Sub + +Sub Printer1_Connected (Success As Boolean) +' If Logger Then Log("Printer1_Connected") + If Success Then + ToastMessageShow("Impresora conectada", False) + skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("MACIMP")) + skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("MACIMP",Starter.mac_impresora)) + LogColor("Impresora conectada", Colors.Green) +' B_IMP2.Enabled = True + impresoraConectada = True + Else +' Msgbox(Printer1.ConnectedErrorMsg, "Error connecting.") 'ignore +' ToastMessageShow("Error conectando la impresora", False) + LogColor("Error conectando la impresora", Colors.Red) + errorImpresora = errorImpresora + 1 + If errorImpresora > 1 Then + Starter.MAC_IMPRESORA = "0" + errorImpresora = 0 + End If + End If +End Sub + +Private Sub b_Tarifa_Click + p_tar_f.Visible = True + b_entrada.Visible = False + b_salida.Visible = False + b_Tarifa.Visible = False + b_resdia.Visible = False +End Sub + +Private Sub b_tar_can_Click + p_tar_f.Visible = False + b_entrada.Visible = True + b_salida.Visible = True + b_resdia.Visible = True + + b_Tarifa.Visible = True +End Sub + +Private Sub b_tar_in_Click + + If et_tar_f.Text <> "" Then + + c = skmt.ExecQuery("SELECT TMP_TAR_H FROM TMP_TARIFA") + If c.RowCount = 0 Then + + skmt.ExecNonQuery2("INSERT INTO TMP_TARIFA (TMP_TAR_H) VALUES (?)", Array As Object(et_tar_f.Text)) + MsgboxAsync("Tarifa guardada", "AVISO") + p_tar_f.Visible = False + p_estacionamiento.Visible = True + b_entrada.Visible = True + b_salida.Visible = True + b_Tarifa.Visible = True + + Else If c.RowCount > 0 Then + + skmt.ExecNonQuery($"UPDATE TMP_TARIFA SET TMP_TAR_H = '${et_tar_f.Text}' "$) + MsgboxAsync("Tarifa actualizada", "AVISO") + p_tar_f.Visible = False + p_estacionamiento.Visible = True + b_entrada.Visible = True + b_salida.Visible = True + b_Tarifa.Visible = True + + End If + Else + MsgboxAsync("Ingrese la tarifa por hora", "AVISO") + End If + c.Close +End Sub + +Private Sub b_resdia_Click + p_res.Visible = True + p_estacionamiento.Visible = False + + c = skmt.ExecQuery("SELECT * FROM TMP_INFO_EnSal") + l_totales.Text = c.RowCount + + + Dim fecha As String = Subs.traeFecha + Dim fechaHora() As String = Regex.Split(" ", fecha) + Log(fechaHora(0)) + Private d1 As Cursor = skmt.ExecQuery($"SELECT * FROM HIST_PLACAS WHERE SALIDA LIKE '%${fechaHora(0)}%'"$) + l_totalsal.Text = d1.RowCount + + Private d2 As Cursor = skmt.ExecQuery($"SELECT IFNULL(SUM(MONTO),0) AS MONTO FROM HIST_PLACAS WHERE SALIDA LIKE '%${fechaHora(0)}%'"$) + d2.Position = 0 + l_montoto.Text = d2.GetString("MONTO") + d2.Close + +End Sub + +Private Sub b_rescan_Click + p_res.Visible = False + p_estacionamiento.Visible = True +End Sub + +Private Sub b_resacep_Click + +End Sub \ No newline at end of file