Exemplo n.º 1
0
        private byte[] criaPacoteDados(byte checkSumCabecalho, Employee employee)
        {
            byte[] nome         = Conversor.stringToByteArray(employee.employeeName, 52);           // Campo Nome 52 bytes;
            byte[] pis          = Conversor.pisToByte(Conversor.SomenteNumeros(employee.pisPasep)); // Campo PIS 6 bytes;
            byte[] reservado    = new byte[4];                                                      // Campo Reservado 4 bytes;
            String cartaoString = "";

            byte[] cartao = Conversor.stringParaBytes(cartaoString != null && cartaoString.Length > 0 ? cartaoString : "0", 20); // Campo Cartão 20 bytes;
            byte[] codigo = Conversor.intToByteArray(employee.idEmployee, 3);                                                    // Campo Código 3 bytes;
            byte[] mestre = new byte[1];                                                                                         // Campo Mestre 1 byte;
            //String senhaStr = funcionario.getSenha();
            byte[] senha = new byte[3];

            /*if (senhaStr != null && !senhaStr.equals("000000") && senhaStr.length() < 7)
             * {
             *  senha = funcionario.getSenhaArray(); // Campo Senha 3 bytes;
             * }*/
            byte[] verifica1ToN = new byte[1]; // Campo Verifica 1 byte;
            byte[] cmp          = new byte[1]; // Campo adicional 1 byte;
            byte[] requisicao   = new byte[] { };
            requisicao = ProtocolUtils.merge(nome, pis, reservado, cartao, codigo, mestre, senha, verifica1ToN, cmp);
            byte checksum = ProtocolUtils.getChecksum(ProtocolUtils.merge(requisicao, new byte[] { checkSumCabecalho, Convert.ToByte(CommandCodes.END) }));

            requisicao = ProtocolUtils.merge(requisicao, new byte[] { checksum });
            return(requisicao);
        }
Exemplo n.º 2
0
        public void StartServer(Server serverConfig, Context context, Action <Connection> onNewClient)
        {
            ValidateProtocolName(serverConfig);

            ServerConfig config = new ServerConfig();

            config.Port             = ProtocolUtils.retrieveProtocolSetting(serverConfig, "port", 34837);
            config.MaxRequestLength = 100000;

            string host = ProtocolUtils.retrieveProtocolSetting(serverConfig, "host", "Any");

            if (host != "Any")
            {
                IPAddress[] ipAddresses = Dns.GetHostAddresses(host);
                if (ipAddresses.Length == 0)
                {
                    throw new Error(ErrorCode.CONNECTION_ERROR, "Cannot identify IP address by hostname.");
                }
                config.Ip = ipAddresses[0].ToString();  // we take first entry as it does not matter which one is used
            }
            else
            {
                config.Ip = "Any";
            }

            IWSJServer server = wsjServerFactory.Construct(onNewClient);

            server.Setup(config);
            server.Start();
        }
Exemplo n.º 3
0
        public void StartServer(Server serverConfig, Context context, Action <Connection> onNewClient)
        {
            ValidateProtocolName(serverConfig);

            int    port = ProtocolUtils.retrieveProtocolSetting(serverConfig, "port", 34838);
            string host = ProtocolUtils.retrieveProtocolSetting(serverConfig, "host", "Any");

            IPAddress localaddr;

            if (host != "Any")
            {
                IPAddress[] ipAddresses = Dns.GetHostAddresses(host);
                if (ipAddresses.Length == 0)
                {
                    throw new Error(ErrorCode.CONNECTION_ERROR, "Cannot identify IP address by hostname.");
                }
                localaddr = ipAddresses[0];  // we take first entry as it does not matter which one is used
            }
            else
            {
                localaddr = IPAddress.Any;
            }

            // Create connection listener.
            TcpListener listener = new TcpListener(localaddr, port);

            listener.Start();

            // Wait for the first connection asynchronously.
            var serverState = new AsyncServerState {
                Listener = listener, Callback = onNewClient
            };

            listener.BeginAcceptTcpClient(CreateBPConnection, serverState);
        }
Exemplo n.º 4
0
        private void ValidateProtocolName(Server serverConfig)
        {
            string protocol = ProtocolUtils.retrieveProtocolSetting <string>(serverConfig, "name", null);

            if (protocol != "websocket-json")
            {
                throw new Error(ErrorCode.CONNECTION_ERROR, "Given сonfig is not for websocket-json protocol.");
            }
        }
Exemplo n.º 5
0
 private void leTodosFuncionarios()
 {
     byte[] buffer = criarPacoteCabecalho(CommandCodes.START_PC, CommandCodes.LER_FUNCIONARIO, new byte[6],
                                          new byte[2], new byte[6], (byte)0x00, CommandCodes.END);
     sendBuffer(buffer, true, tcp);
     // Lê e trata 1º cabeçalho
     byte[] respostaREP = this.lerEtratarResposta(Protocol.QTD_BYTES_CABECALHO_CRIPTOGRAFADO);
     if (errorCommand.getErro() == ErrorCommand.SUCESSO)
     {
         int qtdFuncionarios = Conversor.ByteArrayToint(ProtocolUtils.copyOfRange(respostaREP,
                                                                                  Protocol.INDICE_INICIO_PARAMETRO,
                                                                                  Protocol.INDICE_FIM_PARAMETRO + 1));
         int    i = 1;
         byte[] total;
         byte[] atual;
         while (i <= qtdFuncionarios &&
                (ErrorCommand.SUCESSO == errorCommand.getErro() || ErrorCommand.DADOS_OK == errorCommand.getErro()))
         {
             // Lê e trata cabeçalho dos dados
             respostaREP = this.lerEtratarResposta(Protocol.QTD_BYTES_FUNCIONARIO);
             if (errorCommand.getErro() == ErrorCommand.DADOS_OK)
             {
                 // Lê os dados do funcionário
                 respostaREP = ProtocolUtils.copyOfRange(respostaREP, Protocol.QTD_BYTES_CABECALHO_DADOS, respostaREP.Length);
                 int qtdBytesRecebidos = -1;
                 if (respostaREP != null)
                 {
                     qtdBytesRecebidos = respostaREP.Length;
                 }
                 if (Protocol.QTD_BYTES_FUNCIONARIO - Protocol.QTD_BYTES_CABECALHO_DADOS == qtdBytesRecebidos)
                 {
                     errorCommand = this.tratarResposta(0, respostaREP, 0, 0);
                     if (ErrorCommand.SUCESSO == errorCommand.getErro() || ErrorCommand.DADOS_OK == errorCommand.getErro())
                     {
                         listaFuncionariosLidos.Add(funcionarioLido);
                     }
                 }
                 // Envia pacote de confirmação OK da leitura de funcionário
                 total  = Conversor.intToByteArray2(qtdFuncionarios);
                 atual  = Conversor.intToByteArray2(i);
                 buffer = criarPacoteCabecalho(CommandCodes.START_PC, CommandCodes.LER_FUNCIONARIO,
                                               new byte[] { total[0], total[1], atual[0], atual[1] }, new byte[4],
                                               new byte[6], (byte)ErrorCommand.DADOS_OK, CommandCodes.END);
                 sendBuffer(buffer, true, tcp);
             }
             i++;
         }
     }
 }
Exemplo n.º 6
0
        public void OpenConnection(Server serverConfig, Context context, Action <Connection> onConnected)
        {
            ValidateProtocolName(serverConfig);

            int    port = ProtocolUtils.retrieveProtocolSetting(serverConfig, "port", -1);
            string host = ProtocolUtils.retrieveProtocolSetting(serverConfig, "host", (string)null);

            if (port == -1 || host == null)
            {
                throw new Error(ErrorCode.CONNECTION_ERROR, "No port and/or IP address is present in configuration.");
            }

            var socketAdapter = new BPSocketAdapter(host, port);

            onConnected(new WSJConnection(socketAdapter));
            socketAdapter.Open();
        }
        private byte[] criaPacoteDados(byte checkSumCabecalho, byte[] cpf, String pisString)
        {
            byte[] nome         = Conversor.stringToByteArray("nome", 52);                  // Campo Nome 52 bytes;
            byte[] pis          = Conversor.pisToByte(Conversor.SomenteNumeros(pisString)); // Campo PIS 6 bytes;
            byte[] reservado    = new byte[4];                                              // Campo Reservado 4 bytes;
            byte[] cartao       = Conversor.stringParaBytes("0", 20);                       // Campo Cartão 20 bytes;
            byte[] codigo       = Conversor.stringParaBytes("0", 3);                        // Campo Código 3 bytes;
            byte[] mestre       = Conversor.stringParaBytes("0", 1);                        // Campo Mestre 1 byte;
            byte[] senha        = Conversor.stringParaBytes("0", 3);                        // Campo Senha 3 bytes;
            byte[] verifica1ToN = new byte[1];                                              // Campo Verifica 1 byte;
            byte[] cmp          = new byte[1];                                              // Campo cmp 1 byte;
            byte[] requisicao   = new byte[] { };
            requisicao = ProtocolUtils.merge(nome, pis, reservado, cartao, codigo, mestre, senha, verifica1ToN, cmp, cpf);
            byte checksum = ProtocolUtils.getChecksum(ProtocolUtils.merge(requisicao, new byte[] { checkSumCabecalho, Convert.ToByte(CommandCodes.END) }));

            requisicao = ProtocolUtils.merge(requisicao, new byte[] { checksum });
            return(requisicao);
        }
Exemplo n.º 8
0
        public void OpenConnection(Server serverConfig, Context context, Action <Connection> onConnected)
        {
            ValidateProtocolName(serverConfig);

            int    port = ProtocolUtils.retrieveProtocolSetting(serverConfig, "port", -1);
            string host = ProtocolUtils.retrieveProtocolSetting(serverConfig, "host", (string)null);

            if (port == -1 || host == null)
            {
                throw new Error(ErrorCode.CONNECTION_ERROR, "No port and/or IP address is present in configuration.");
            }

            ISocket socket = webSocketFactory.Construct("ws://" + host + ":" + port + "/");

            socket.Opened += (sender, e) => onConnected(new WSJConnection(socket));
            socket.Error  += (sender, e) => {
                logger.WarnException("Error in connection to " + host + ":" + port, e.Exception);
            };
            socket.Open();
        }
Exemplo n.º 9
0
 private void leFuncionarioPorPIS(String pis)
 {
     byte[] buffer = criarPacoteCabecalho(CommandCodes.START_PC, CommandCodes.LER_FUNCIONARIO,
                                          Conversor.pisToByte(pis), new byte[2], new byte[6], (byte)0x00, CommandCodes.END);
     sendBuffer(buffer, true, tcp);
     // Lê e trata 1º cabeçalho
     byte[] respostaREP = this.lerEtratarResposta(Protocol.QTD_BYTES_CABECALHO_CRIPTOGRAFADO);
     if (errorCommand.getErro() == ErrorCommand.SUCESSO)
     {
         errorCommand.setErro(ErrorCommand.DADOS_OK);
         // Lê e trata cabeçalho dos dados
         respostaREP = this.lerEtratarResposta(Protocol.QTD_BYTES_FUNCIONARIO);
         if (errorCommand.getErro() == ErrorCommand.DADOS_OK)
         {
             // Lê os dados do funcionário
             respostaREP = ProtocolUtils.copyOfRange(respostaREP, Protocol.QTD_BYTES_CABECALHO_DADOS, respostaREP.Length);
             int qtdBytesRecebidos = -1;
             if (respostaREP != null)
             {
                 qtdBytesRecebidos = respostaREP.Length;
             }
             if (Protocol.QTD_BYTES_FUNCIONARIO - Protocol.QTD_BYTES_CABECALHO_DADOS == qtdBytesRecebidos)
             {
                 errorCommand = this.tratarResposta(0, respostaREP, 0, 0);
                 // Envia pacote de confirmação OK da leitura de funcionário
                 buffer = criarPacoteCabecalho(CommandCodes.START_PC, CommandCodes.LER_FUNCIONARIO,
                                               new byte[] { 0x00, (byte)1, 0x00, (byte)1 }, new byte[4],
                                               new byte[6], (byte)ErrorCommand.DADOS_OK, CommandCodes.END);
                 sendBuffer(buffer, true, tcp);
                 if (ErrorCommand.SUCESSO == errorCommand.getErro() || ErrorCommand.DADOS_OK == errorCommand.getErro())
                 {
                     listaFuncionariosLidos.Add(funcionarioLido);
                 }
             }
         }
     }
     else if (errorCommand.getErro() == ErrorCommand.PIS_INEXISTENTE)
     {
         listaPisNaoEncontrados.Add(pis);
     }
 }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            ProtocolUtils.AddToProtocol("Herzlich Willkommen bei dem Zahlensysteme-Rechner!", ProtocolMessageType.Info);
            ProtocolUtils.AddToProtocol("Um ihre Berechnung zu starten geben sie bitte einen Term ein.", ProtocolMessageType.Info);
            ProtocolUtils.AddToProtocol("Die Grundrechenarten + - * / und Klammersetzung werden unterstüzt.", ProtocolMessageType.Info);
            ProtocolUtils.AddToProtocol("Bei Eingabe einer Zahl wird diese in alle unterstützten Zahlensysteme umgewandelt.", ProtocolMessageType.Info);
            ProtocolUtils.AddToProtocol("Der Taschenrechner unterstützt folgende Zahlensysteme, um diese zu verwenden verwenden sie folgende Präfixe:", ProtocolMessageType.Info);
            ProtocolUtils.AddToProtocol("binär: b_(zahl),", ProtocolMessageType.Info);
            ProtocolUtils.AddToProtocol("oktal: o_(zahl),", ProtocolMessageType.Info);
            ProtocolUtils.AddToProtocol("dezimal: d_(zahl),", ProtocolMessageType.Info);
            ProtocolUtils.AddToProtocol("hexadezimal: h_(zahl)", ProtocolMessageType.Info);
            do
            {
                ConsoleUtils.BeginWindow();
                ProtocolUtils.RefreshWindowFromProtocol();
                ConsoleUtils.BeginLine();
                ConsoleUtils.WriteLineContent("> ");
                //save coordinates
                int cursorX = Console.CursorLeft;
                int cursorY = Console.CursorTop;
                ConsoleUtils.EndLine();
                ConsoleUtils.EndWindow();
                Console.SetCursorPosition(cursorX, cursorY);


                //lese benutzereingabe ein
                string input = Console.ReadLine();

                string displayInput = "> " + input;
                ProtocolUtils.AddToProtocol(displayInput, ProtocolMessageType.Info);
                try
                {
                    // Zerlege die Benutzereingabe in Tokens
                    InputToken[] tokens = InputUtils.CreateTokensFromInput(input);

                    //an sonsten sollte dies ein term sein(länge 0 ist kein problem)
                    //versuche den Term zu evaluieren
                    Operand result = CalculationUtils.CalculateTerm(tokens);
                    //gib das Ergebnis aus
                    ConversionUtils.ConvertNumber(result);
                }
                //fange ungültige Operationen auf, diese entstehen wenn Leere stacks gepoppt werden
                //passiert wenn die eingabe syntax fehler enthielt
                catch (InvalidOperationException)
                {
                    ProtocolUtils.AddToProtocol("Syntax Fehler", ProtocolMessageType.Error);
                }// Durch null teilen
                catch (DivideByZeroException)
                {
                    ProtocolUtils.AddToProtocol("Durch 0 teilen nicht möglich.", ProtocolMessageType.Error);
                }
                //fange sonstige Exceptions auf und gib die nachricht auf der konsole aus
                catch (Exception e)
                {
                    ProtocolUtils.AddToProtocol(e.Message, ProtocolMessageType.Error);
                }



                ProtocolUtils.AddToProtocol("Möchten Sie noch eine Berechnung durchführen? (j/n)", ProtocolMessageType.Info);

                ConsoleUtils.BeginWindow();
                ProtocolUtils.RefreshWindowFromProtocol();
                ConsoleUtils.EndWindow();
                //wiederhole solange der benutzer kein kleines n eintippt
            } while (Console.ReadKey().KeyChar != 'n');

            Console.Clear();

            string filename = "rechenprotokoll.txt";

            ProtocolUtils.WriteProtocolToFile(filename);
            Console.WriteLine("Protokoll gespeichert. Dateiname: " + filename);
        }
Exemplo n.º 11
0
 /// <summary>
 /// Reads a large amount of data into the input buffer.
 /// </summary>
 public int ReadData(int offset, int size)
 {
     return(ProtocolUtils.ReadData(NetStream, TcpClient.ReceiveTimeout, InBuf, offset, size));
 }
Exemplo n.º 12
0
        public ErrorCommand execute(String ip, String porta, int nsr)
        {
            errorCommand = new ErrorCommand();
            tcp          = null;
            try
            {
                tcp = new Tcp(ip, Convert.ToInt16(porta));
            }
            catch (IOException e) {
                errorCommand.setErro(ErrorCommand.COMUNICACAO_NAO_ESTABELECIDA);
                return(errorCommand);
            }
            try
            {
                try
                {
                    /** Quando é informado um NSR maior do que o último gravado no REP,
                     * o REP retorna o flag 0x96 (O Frame recebido contém erro).
                     **/
                    byte[] buffer = criarPacoteCabecalho(CommandCodes.START_PC, CommandCodes.LER_MARCACAO,
                                                         Conversor.intToByteArray(nsr, 4),
                                                         Conversor.intToByteArray(Protocol.TAMANHO_PACOTE_MARCACOES, 4),
                                                         new byte[6], (byte)0x00, CommandCodes.END);
                    sendBuffer(buffer, true, tcp);
                    // Lê e trata 1º cabeçalho
                    byte[] respostaREP       = this.lerEtratarResposta(Protocol.QTD_BYTES_CABECALHO_CRIPTOGRAFADO);
                    byte[] totalMarcacoes    = ProtocolUtils.copyOfRange(respostaREP, Protocol.INDICE_INICIO_PARAMETRO, Protocol.INDICE_INICIO_PARAMETRO + 4);
                    int    totalMarcacoesInt = Conversor.ByteArrayToint(totalMarcacoes);
                    // Cálculo necessário devido ao último pacote ser de tamanho variável
                    int qtdMarcacoesUltimoPacote = totalMarcacoesInt % Protocol.TAMANHO_PACOTE_MARCACOES;
                    int qtdBytesASeremLidos      = 0;
                    if (errorCommand.getErro() == ErrorCommand.SUCESSO)
                    {
                        errorCommand.setErro(ErrorCommand.DADOS_OK);
                        int    pacoteAtual = -1;
                        byte[] atual;
                        listaMarcacoes = new LinkedList <Marking>();
                        while (pacoteAtual < totalPacotes &&
                               (ErrorCommand.SUCESSO == errorCommand.getErro() || ErrorCommand.DADOS_OK == errorCommand.getErro()))
                        {
                            // Lê e trata cabeçalho dos dados
                            if (totalMarcacoesInt < Protocol.TAMANHO_PACOTE_MARCACOES ||
                                (pacoteAtual != -1 && (pacoteAtual + 1) == totalPacotes && qtdMarcacoesUltimoPacote > 0))
                            { // último pacote a ser recebido
                              //qtdBytesASeremLidos = AES.defineTamanhoPacote(Protocol.QTD_BYTES_CABECALHO_DADOS + Protocol.QTD_BYTES_MARCACAO * qtdMarcacoesUltimoPacote);
                            }
                            else
                            {
                                qtdBytesASeremLidos = Protocol.QTD_BYTES_PACOTES_MARCACOES;
                            }
                            respostaREP = this.lerEtratarResposta(qtdBytesASeremLidos);
                            if (errorCommand.getErro() == ErrorCommand.DADOS_OK)
                            {
                                // Verificando o total de pacotes a serem lidos do REP
                                byte[] total = ProtocolUtils.copyOfRange(respostaREP, Protocol.INDICE_INICIO_PARAMETRO, Protocol.INDICE_INICIO_PARAMETRO + 2);
                                totalPacotes = Conversor.ByteArrayToint(total);
                                // Verificando o pacote atual
                                atual       = ProtocolUtils.copyOfRange(respostaREP, Protocol.INDICE_FIM_PARAMETRO - 1, Protocol.INDICE_FIM_PARAMETRO + 1);
                                pacoteAtual = Conversor.ByteArrayToint(atual);

                                // Lê os pacotes de marcação de ponto
                                respostaREP = ProtocolUtils.copyOfRange(respostaREP, Protocol.QTD_BYTES_CABECALHO_DADOS, respostaREP.Length);
                                int qtdBytesRecebidos = -1;
                                if (respostaREP != null)
                                {
                                    qtdBytesRecebidos = respostaREP.Length;
                                }
                                if (qtdBytesASeremLidos - Protocol.QTD_BYTES_CABECALHO_DADOS == qtdBytesRecebidos)
                                {
                                    errorCommand = this.tratarResposta(0, respostaREP, 0, 0);
                                }
                                if (errorCommand.getErro() == ErrorCommand.FIM_LEITURA_MARCACOES)
                                {
                                    atual[0] = total[0];
                                    atual[1] = total[1];
                                }
                                // Envia comando de leitura do(s) próximo(s) pacote(s) de marcação de ponto
                                buffer = criarPacoteCabecalho(CommandCodes.START_PC, CommandCodes.LER_MARCACAO,
                                                              new byte[] { total[0], total[1], atual[0], atual[1] }, new byte[4],
                                                              new byte[6], (byte)ErrorCommand.DADOS_OK, CommandCodes.END);

                                sendBuffer(buffer, true, tcp);
                            }
                        }
                        if (errorCommand.getErro() == ErrorCommand.DADOS_OK ||
                            errorCommand.getErro() == ErrorCommand.FIM_LEITURA_MARCACOES)
                        {
                            errorCommand.setErro(ErrorCommand.SUCESSO);
                        }
                    }
                }
                catch (Exception e)
                {
                    errorCommand.setErro(ErrorCommand.OCORREU_EXCECAO);
                }
                tcp.finalizaConexao();
            }
            catch (Exception e)
            {
                errorCommand.setErro(ErrorCommand.ERRO_FINALIZAR_CONEXAO);
            }

            return(errorCommand);
        }
Exemplo n.º 13
0
        public ErrorCommand execute(String ip, String porta, List <Employee> employees)
        {
            errorCommand = new ErrorCommand();
            tcp          = null;
            try
            {
                tcp = new Tcp(ip, Convert.ToInt16(porta));
            }
            catch (IOException e) {
                errorCommand.setErro(ErrorCommand.COMUNICACAO_NAO_ESTABELECIDA);
                return(errorCommand);
            }

            try
            {
                try
                {
                    int totalFuncionarios = employees.Count();
                    int funcionarioAtual  = 1;
                    int flagErro          = ErrorCommand.SUCESSO;
                    while (funcionarioAtual <= totalFuncionarios && (ErrorCommand.SUCESSO == errorCommand.getErro() || ErrorCommand.DADOS_OK == errorCommand.getErro()))
                    {
                        Employee employee = employees[funcionarioAtual - 1];
                        // Exclusão do funcionário antes de adicioná-lo no REP
                        CommandDeleteEmployee excluiFuncionario = new CommandDeleteEmployee(tcp);

                        errorCommand = excluiFuncionario.execute(ip, porta, cpf, employee.pisPasep);
                        // Envio do funcionário para o REP
                        if (flagErro == ErrorCommand.SUCESSO || flagErro == ErrorCommand.IDENTIFICADOR_RECUSADO || flagErro == ErrorCommand.PIS_INEXISTENTE)
                        {
                            byte[] bytesCPF = Conversor.cpfToByte(cpf);
                            byte[] cabecalhoDadosGravaFuncionario = Command.criarPacoteCabecalho(CommandCodes.START_PC, CommandCodes.ENVIAR_FUNCIONARIO,
                                                                                                 new byte[] { 0x00, 0x00, 0x00, 0x01 },
                                                                                                 new byte[4], bytesCPF,
                                                                                                 (byte)ErrorCommand.ADICIONAR, CommandCodes.END);
                            // Envia o cabeçalho
                            Command.sendBuffer(cabecalhoDadosGravaFuncionario, true, tcp);
                            // Lê e trata 1º cabeçalho
                            lerEtratarResposta(Protocol.QTD_BYTES_CABECALHO_CRIPTOGRAFADO);
                            if (errorCommand.getErro() == ErrorCommand.SUCESSO)
                            {
                                cabecalhoDadosGravaFuncionario = Command.criarPacoteCabecalho(CommandCodes.START_PC, CommandCodes.ENVIAR_FUNCIONARIO,
                                                                                              new byte[] { 0x00, 0x01, 0x00, 0x01 },
                                                                                              new byte[] { 0x00, 0x00, 0x00, 0x61 },
                                                                                              bytesCPF, (byte)ErrorCommand.DADOS_OK, CommandCodes.END);

                                byte   checkSumCabecalho     = cabecalhoDadosGravaFuncionario[Protocol.QTD_BYTES_CABECALHO_DADOS - 2];
                                byte[] dadosGravaFuncionario = criaPacoteDados(checkSumCabecalho, employee);

                                // Envia os dados do funcionário
                                Command.sendBuffer(ProtocolUtils.merge(cabecalhoDadosGravaFuncionario, dadosGravaFuncionario), true, tcp);
                                // Lê e trata 2ª resposta do REP
                                lerEtratarResposta(Protocol.QTD_BYTES_CABECALHO_CRIPTOGRAFADO);
                            }
                        }
                        funcionarioAtual++;
                    }
                }
                catch (Exception e)
                {
                    errorCommand.setErro(ErrorCommand.OCORREU_EXCECAO);
                }
                tcp.finalizaConexao();
            }
            catch (Exception e)
            {
                errorCommand.setErro(ErrorCommand.ERRO_FINALIZAR_CONEXAO);
            }

            return(errorCommand);
        }
Exemplo n.º 14
0
        public ErrorCommand execute(String ip, String porta, String cpf, String pis)
        {
            Boolean      finalizarConexao = false;
            ErrorCommand errorCommand     = new ErrorCommand();

            if (tcp == null)
            {
                try
                {
                    finalizarConexao = true;
                    tcp = new Tcp(ip, Convert.ToInt16(porta));
                }
                catch (IOException e) {
                    errorCommand.setErro(ErrorCommand.COMUNICACAO_NAO_ESTABELECIDA);
                    return(errorCommand);
                }
            }

            try
            {
                try
                {
                    byte[] bytesCpf = Conversor.cpfToByte(cpf);
                    byte[] cabecalhoDadosGravaFuncionario = criarPacoteCabecalho(CommandCodes.START_PC, CommandCodes.ENVIAR_FUNCIONARIO,
                                                                                 new byte[] { 0x00, 0x00, 0x00, 0x01 }, new byte[4], bytesCpf,
                                                                                 (byte)ErrorCommand.EXCLUIR, CommandCodes.END);
                    // Envia o cabeçalho
                    sendBuffer(cabecalhoDadosGravaFuncionario, true, tcp);
                    // Lê 1ª resposta do REP
                    byte[] retornoReal       = readAnswer(tcp, Protocol.QTD_BYTES_CABECALHO_CRIPTOGRAFADO);
                    int    qtdBytesRecebidos = -1;
                    if (retornoReal != null)
                    {
                        qtdBytesRecebidos = retornoReal.Length;
                    }
                    // Trata a 1ª resposta do REP
                    errorCommand = tratarResposta(CommandCodes.ENVIAR_FUNCIONARIO, retornoReal, qtdBytesRecebidos, Protocol.QTD_BYTES_CABECALHO_CRIPTOGRAFADO);
                    if (errorCommand.getErro() == ErrorCommand.SUCESSO)
                    {
                        cabecalhoDadosGravaFuncionario = criarPacoteCabecalho(CommandCodes.START_PC, CommandCodes.ENVIAR_FUNCIONARIO,
                                                                              new byte[] { 0x00, 0x01, 0x00, 0x01 }, new byte[] { 0x00, 0x00, 0x00, 0x61 },
                                                                              bytesCpf, (byte)ErrorCommand.DADOS_OK, CommandCodes.END);

                        byte   checkSumCabecalho     = cabecalhoDadosGravaFuncionario[cabecalhoDadosGravaFuncionario.Length - 2];
                        byte[] dadosGravaFuncionario = criaPacoteDados(checkSumCabecalho, bytesCpf, pis);

                        // Envia os dados do funcionário
                        sendBuffer(ProtocolUtils.merge(cabecalhoDadosGravaFuncionario, dadosGravaFuncionario), true, tcp);
                        retornoReal = new byte[Protocol.QTD_BYTES_CABECALHO_CRIPTOGRAFADO];
                        // Lê 2ª resposta do REP
                        retornoReal       = readAnswer(tcp, Protocol.QTD_BYTES_CABECALHO_CRIPTOGRAFADO);
                        qtdBytesRecebidos = -1;
                        if (retornoReal != null)
                        {
                            qtdBytesRecebidos = retornoReal.Length;
                        }
                        // Trata a 2ª resposta do REP
                        errorCommand = tratarResposta(CommandCodes.ENVIAR_FUNCIONARIO, retornoReal, qtdBytesRecebidos, Protocol.QTD_BYTES_CABECALHO_CRIPTOGRAFADO);
                    }
                }
                catch (Exception e)
                {
                    errorCommand.setErro(ErrorCommand.OCORREU_EXCECAO);
                }
                if (finalizarConexao)
                {
                    tcp.finalizaConexao();
                }
            }
            catch (Exception e)
            {
                errorCommand.setErro(ErrorCommand.ERRO_FINALIZAR_CONEXAO);
            }

            return(errorCommand);
        }