From 96d6f05b0321e2166f8e6ee3d34f337dfcd8d255 Mon Sep 17 00:00:00 2001 From: bfsc19 <bfsc19@inf.ufpr.br> Date: Mon, 27 Feb 2023 01:15:01 -0300 Subject: [PATCH] feature: adicionada cores e textos na interface --- headers/client.h | 95 +++++++++++++++++------------------- headers/conexao.h | 19 ++++---- headers/cores.h | 23 +++++++++ headers/server.h | 122 ++++++++++++++++++++++++---------------------- testecor.cpp | 24 +++++++++ todo.txt | 4 +- 6 files changed, 166 insertions(+), 121 deletions(-) create mode 100644 headers/cores.h create mode 100644 testecor.cpp diff --git a/headers/client.h b/headers/client.h index e960dfa..05638ff 100644 --- a/headers/client.h +++ b/headers/client.h @@ -21,15 +21,8 @@ // include local #include "conexao.h" +#include "cores.h" #include "frame.h" - -vector<string> CMD_HELP = {"H", "help", "-h", "HELP", "Help", - "-H", "ajuda", "Ajuda", "AJUDA"}; -vector<string> CMD_EXIT = {"exit", "-e", "EXIT", "Exit", - "-E", "sair", "Sair", "SAIR"}; -vector<string> CMD_SEND = {"send", "-s", "SEND", "Send", - "-S", "enviar", "Enviar", "ENVIAR"}; - using namespace std; class client { @@ -80,7 +73,7 @@ frame *client::receive_ack(frame *f) { do { ack_res = socket->receive_frame(); if (ack_res && ack_res->get_tipo() == ERRO) { - cout << "Espaco insulficiente no destino\n"; + cout << BOLDYELLOW << "Espaco insulficiente no destino\n" << RESET; return NULL; } } while (ack_res && @@ -102,41 +95,40 @@ int client::send_frame_socket(frame *f) { } while (ack_res == NULL && retries < NUM_RETRIES); if (ack_res == NULL && retries == NUM_RETRIES) { - cout << "Desisti de enviar\n"; + // cout << "Desisti de enviar\n"; ->log return 0; } - cout << "\tACK recebido:\n"; - ack_res->imprime(HEX); + // cout << "\tACK recebido:\n"; ->log + // ack_res->imprime(HEX); return 1; } - // Inicia a transmissao com o servidor int client::start_transmission() { - cout << "\tIniciando transmissao\n"; + // cout<< YELLOW << "\tIniciando transmissao\n" << RESET; ->log frame *ini = new frame(INIT, 0, vector<char>(1, 0)); int enviado = send_frame_socket(ini); if (!enviado) { - cout << "\tFalha ao iniciar a transmissao\n"; + // cout<< BOLDRED << "\tFalha ao iniciar a transmissao\n" << RESET; ->log return 0; } - cout << "\tTransmissao iniciada com sucesso\n"; + // cout<< GREEN << "\tTransmissao iniciada com sucesso\n" << RESET; ->log return 1; } // Encerra a transmissao com o servidor int client::end_transmission() { - cout << "\tEncerrando a transmissao\n"; + // cout << "\tEncerrando a transmissao\n"; ->log frame *end = new frame(FIMT, 0, vector<char>(1, 0)); int enviado = send_frame_socket(end); if (!enviado) { - cout << "\tFalha ao encerrar a transmissao\n"; + // cout << "\tFalha ao encerrar a transmissao\n"; ->log return 0; } - cout << "\tTransmissao encerrada com sucesso\n"; + // cout << "\tTransmissao encerrada com sucesso\n"; ->log return 1; } @@ -154,20 +146,20 @@ int client::send_frames(vector<frame *> frames) { // Envia um frame por vez for (size_t i = 0; i < frames.size(); i++) { - cout << "\tEnviando frame\n"; - frames[i]->imprime(DEC); + // cout << "\tEnviando frame\n"; ->log + // frames[i]->imprime(DEC); int enviado = send_frame_socket(frames[i]); if (!enviado) { - cout << "\tFalha ao enviar o frame\n"; + // cout << "\tFalha ao enviar o frame\n"; ->log return 0; } - cout << "\tFrame enviado com sucesso\n"; + // cout << "\tFrame enviado com sucesso\n"; ->log } if (!end_transmission()) { return 0; } - cout << "\tTerminou de enviar todos os frames\n"; + // cout << "\tTerminou de enviar todos os frames\n"; ->log return 1; } @@ -211,7 +203,7 @@ int client::send_message(vector<char> data, int type) { string client::calc_file_size(string fileName) { struct stat buffer; if (stat(fileName.c_str(), &buffer) == -1) { - cout << "Arquivo inexistente. Operacao abortada\n"; + cout << YELLOW << "\t--Arquivo inexistente. Operacao abortada--\n" << RESET; return {}; } @@ -231,7 +223,6 @@ vector<char> client::read_file(string fileName) { return fileData; } - /** * @brief Send a file through the socket * @@ -241,20 +232,22 @@ void client::send_file() { string fileName; do { - cout << "Digite o nome do arquivo(maximo de " << TAM_DADOS - << " char):\n"; + cout << BOLDWHITE << "Digite o nome do arquivo(maximo de " << TAM_DADOS + << " char):\n" + << RESET; getline(cin, fileName); } while (fileName.size() > TAM_DADOS); fileNameVector.insert(fileNameVector.begin(), fileName.begin(), fileName.end()); + cout << BOLDYELLOW << "\t--Enviando arquivo--\n" << RESET; if (!send_message(fileNameVector, MIDIA)) { - cout << "Falha ao enviar o arquivo\n"; + cout << BOLDRED << "\t--Falha ao enviar o arquivo--\n" << RESET; return; } - cout << "Arquivo enviado com sucesso\n"; + cout << BOLDGREEN << "\t--Arquivo enviado com sucesso--\n" << RESET; } /** @@ -264,14 +257,14 @@ void client::send_file() { */ void client::send_text(string message) { - cout << "Enviando mensagem\n"; + cout << BOLDYELLOW << "\t--Enviando mensagem--\n" << RESET; vector<char> data(message.begin(), message.end()); if (!send_message(data, TEXTO)) - cout << "Limite de timout, mensagem nao foi enviada\n"; - + cout << BOLDRED << "\t--Limite de timout, mensagem nao foi enviada--\n" + << RESET; else - cout << "Mensagem enviada com sucesso\n"; + cout << GREEN << "\t--Mensagem enviada com sucesso--\n" << RESET; } vector<frame *> client::create_frames_midia(vector<char> vectorName) { @@ -296,7 +289,8 @@ vector<frame *> client::create_frames_midia(vector<char> vectorName) { // Cria um vetor com os dados do arquivo vector<char> vectorData = read_file(fileName); if (vectorData.empty()) { - cout << "Falha ao abrir o arquivo para leitura\n"; + cout << BOLDRED << "\t--Falha ao abrir o arquivo para leitura--\n" + << RESET; //->log return vector<frame *>(); } @@ -306,7 +300,7 @@ vector<frame *> client::create_frames_midia(vector<char> vectorName) { // Arruma a sequencia dos frames for (int i = 0; i < framesToSend.size(); i++) - framesToSend[i]->set_seq(i%16); + framesToSend[i]->set_seq(i % 16); return framesToSend; } @@ -346,30 +340,29 @@ bool client::string_has(string str, vector<string> strList) { } char client::string_cmd(string str) { - if (string_has(str, CMD_HELP)) return 'h'; - - if (string_has(str, CMD_EXIT)) return 'e'; - - if (string_has(str, CMD_SEND)) return 's'; - + if (strcmp(str.c_str(), "-h") == 0) return 'h'; + if (strcmp(str.c_str(), "-e") == 0) return 'e'; + if (strcmp(str.c_str(), "-s") == 0) return 's'; return 'm'; } void client::print_help() { - cout << "Comandos disponiveis:\n"; - cout << "help ou -h ou h ou HELP ou Help ou H ou ajuda ou Ajuda ou AJUDA\n"; - cout << "exit ou -e ou e ou EXIT ou Exit ou E ou sair ou Sair ou SAIR\n"; - cout << "send ou -s ou s ou SEND ou Send ou S ou enviar ou Enviar ou " - "ENVIAR\n"; - cout << "para enviar uma mensagem, digite a mensagem e pressione enter\n"; + cout << BOLDBLUE << "\t---Comandos disponiveis---\n" << RESET; + cout << YELLOW + << "para enviar uma mensagem, digite a mensagem e pressione enter\n" + << RESET; + cout << GREEN << "-s: " << WHITE << "envia um arquivo\n" << RESET; + cout << RED << "-e: " << WHITE << "sai do programa\n" << RESET; + cout << BLUE << "-h: " << WHITE << "exibe os comandos disponíveis\n" << RESET; } // ------------------------------- PUBLIC --------------------------------- // void client::run() { int i; + print_help(); while (true) { - cout << " Digite um comando ou mensagem:\n"; + cout << BOLDWHITE << "\nDigite um comando ou mensagem:\n" << RESET; getline(cin, userInput); char userInputCMD = string_cmd(userInput); @@ -380,7 +373,7 @@ void client::run() { break; case 'e': - cout << "Saindo...\n"; + cout << BOLDYELLOW << "\tSaindo...\n" << RESET; exit(0); break; @@ -393,7 +386,7 @@ void client::run() { break; default: - cout << "Comando invalido\n"; + cout << BOLDMAGENTA << "\tComando invalido\n" << RESET; break; } } diff --git a/headers/conexao.h b/headers/conexao.h index 072f624..702e89f 100644 --- a/headers/conexao.h +++ b/headers/conexao.h @@ -20,7 +20,7 @@ // include local #include "frame.h" - +#include "cores.h" using namespace std; #define BYTE "%02x" @@ -92,14 +92,13 @@ frame *conexao::receive_frame() { // for (int i = 0; i < byteRecv; i++) { // cout << hex << (int(bufferReceived[i])&0xff) << " "; // } - cout << "\n"; + // cout << "\n"; if ((byteRecv > 0) && (bufferReceived[0] == INI)) { frame *f = new frame; remove_escapes(bufferReceived, (char *)f); return f; } } while (timestamp() - start <= timeoutMillis); - return NULL; } @@ -117,12 +116,12 @@ int conexao::send_frame(frame *f) { int timeout = 0; int byteSend = send(device, bufferSend, sizeof(frame) * 2, 0); - printf("send %d: ", byteSend); - for (int i = 0; i < byteSend; i++) { - cout << hex << (int(bufferSend[i]) & 0xff) << " "; - } - cout << "\n"; - if (byteSend < 0) { cout << "Erro no sendto" << byteSend << "\n"; } + // printf("send %d: ", byteSend); + // for (int i = 0; i < byteSend; i++) { + // cout << hex << (int(bufferSend[i]) & 0xff) << " "; + // } + // cout << "\n"; + // if (byteSend < 0) { cout << "Erro no sendto" << byteSend << "\n"; } ->log return byteSend; } @@ -167,7 +166,7 @@ int conexao::ConexaoRawSocket(char *device) { soquete = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); /*cria socket*/ if (soquete == -1) { - printf("Erro no Socket, verifique se voce eh root\n"); + cout << BOLDRED <<"\tErro no Socket, verifique se voce eh root\n" << RESET; exit(-1); } diff --git a/headers/cores.h b/headers/cores.h new file mode 100644 index 0000000..ee8f7af --- /dev/null +++ b/headers/cores.h @@ -0,0 +1,23 @@ +#ifndef COLORS_H +#define COLORS_H + +/*RESET TERMINAL COLOR*/ +#define RESET "\033[0m" // reset terminal color +#define BLACK "\033[30m" +#define RED "\033[31m" // erros +#define GREEN "\033[32m" // sucesso +#define YELLOW "\033[33m" // informações para o usuário +#define BLUE "\033[34m" +#define MAGENTA "\033[35m" // warnings +#define CYAN "\033[36m" +#define WHITE "\033[37m" // caixa de texto +#define BOLDBLACK "\033[1m\033[30m" +#define BOLDRED "\033[1m\033[31m" // erros* +#define BOLDGREEN "\033[1m\033[32m" // sucesso* +#define BOLDYELLOW "\033[1m\033[33m" // informações para o usuário* +#define BOLDBLUE "\033[1m\033[34m" +#define BOLDMAGENTA "\033[1m\033[35m" // warnings* +#define BOLDCYAN "\033[1m\033[36m" +#define BOLDWHITE "\033[1m\033[37m" // caixa de texto* + +#endif diff --git a/headers/server.h b/headers/server.h index e2e76cb..18a2854 100644 --- a/headers/server.h +++ b/headers/server.h @@ -22,8 +22,8 @@ // include local #include "conexao.h" -#include "frame.h" #include "cores.h" +#include "frame.h" #define FILE_DESTINATION "./received" @@ -83,7 +83,7 @@ int server::send_ack(frame *fReceive) { int ackSent = 0; ackSent = socket->send_frame(ack); - cout << "ACK enviado\n"; + // cout << "ACK enviado\n"; ->log return ackSent; } @@ -106,7 +106,7 @@ int server::send_nack(frame *fReceive) { int nackSent = 0; nackSent = socket->send_frame(nack); - cout << "NACK enviado\n"; + // cout << "NACK enviado\n"; ->log return nackSent; } @@ -126,14 +126,16 @@ void server::receive_text(frame *f) { textoReceive.append(f->get_dado()); } while (f->get_tipo() != FIMT); - cout << "Mensagem recebida: " << textoReceive << "\n"; + cout << BOLDYELLOW << "\t--Mensagem recebida--\n " << BOLDWHITE + << textoReceive << "\n" + << RESET; } // Verifica o espaco disponivel em disco unsigned long server::chk_available_size() { struct statvfs st; if (statvfs(FILE_DESTINATION, &st) == -1) { - cout << "Erro no statvfs, abortado\n"; + // cout << "Erro no statvfs, abortado\n";->log // send_error(); return -1; } @@ -151,12 +153,12 @@ int server::receive_file_size(frame *f) { crc estiver certo, envia um ack e continua > se estiver errado, envia um nack e espera receber o proximo frame */ - cout << "Recebendo tamanho do frame\n"; + // cout << "Recebendo tamanho do frame\n";->log do { - if ( f->get_tipo() != MIDIA ) { continue; } - if ( f->get_seq() == 0 && verify_crc8(f) ) { break; } - - if ( f->get_seq() != 0 ) + if (f->get_tipo() != MIDIA) { continue; } + if (f->get_seq() == 0 && verify_crc8(f)) { break; } + + if (f->get_seq() != 0) cout << "Sequencia errada\n"; else cout << "Crc errado\n"; @@ -173,16 +175,17 @@ int server::receive_file_size(frame *f) { unsigned long availSize = chk_available_size(); if (availSize == -1) { return -1; } - cout << "Frame file size:" << f->get_dado() << "\n"; + // cout << "Frame file size:" << f->get_dado() << "\n"; ->log int fileSize = stoi(f->get_dado()); if (fileSize > availSize * 0.9) { - cout << "Tamanho do arquivo muito grande, abortado\n"; + cout << BOLDMAGENTA << "\t--Tamanho do arquivo muito grande, abortado--\n" + << RESET; // send_error(); return 0; } - cout << "Espaco suficiente em disco\n"; + // cout << "Espaco suficiente em disco\n"; ->log return 1; } @@ -191,17 +194,17 @@ bool server::create_received_dir() { // check if the directory exists struct stat info; if (stat(FILE_DESTINATION, &info) == 0 && (info.st_mode & S_IFDIR)) { - cout << "Diretorio ja existe\n"; + // cout << "Diretorio ja existe\n"; ->log return true; } // create the directory if (mkdir(FILE_DESTINATION, 0777) == -1) { - cout << "Erro ao criar o diretorio\n"; + cout << RED << "Erro ao criar o diretorio\n" << RESET; return false; } - cout << "Diretorio criado com sucesso\n"; + // cout << "Diretorio criado com sucesso\n"; ->log return true; } @@ -216,19 +219,18 @@ string server::receive_file_name() { > se estiver correto, envia um ack e continua > se estiver errado, envia um nack e espera receber o proximo frame */ - cout << "Recebendo nome do arquivo\n"; + // cout << "Recebendo nome do arquivo\n";->log do { - cout << "Aguardando frame\n"; + // cout << "Aguardando frame\n";->log fReceive = receive_frame_socket(); if (!fReceive) { return string{}; } - cout << "Frame recebido\n"; + // cout << "Frame recebido\n";->log if (fReceive->get_tipo() != MIDIA) { continue; } - if ( fReceive->get_seq() != 1 ) - { - cout << "Sequencia errada\n"; + if (fReceive->get_seq() != 1) { + // cout << "Sequencia errada\n";->log fReceive->set_seq(0); send_ack(fReceive); continue; @@ -236,21 +238,20 @@ string server::receive_file_name() { if (verify_crc8(fReceive)) { break; } - cout << "Crc invalido, aguardando retransmissao\n"; + // cout << "Crc invalido, aguardando retransmissao\n"; ->log } while (true); - cout << "Nome do arquivo recebido com sucesso\n"; - cout << "Nome do arquivo: " << fReceive->get_dado() << "\n"; + // cout << "Nome do arquivo recebido com sucesso\n"; ->log + // cout << "Nome do arquivo: " << fReceive->get_dado() << "\n"; ->log return string(fReceive->get_dado()); } bool server::verify_seq(int seq, int lastSeq) { - cout << "seq: " << seq << " lastSeq: " << dec << lastSeq << "\n"; - if ( seq == 0 ) - { - if ( lastSeq != 15 ) { return false; } + // cout << "seq: " << seq << " lastSeq: " << dec << lastSeq << "\n"; ->log + if (seq == 0) { + if (lastSeq != 15) { return false; } return true; } @@ -264,14 +265,18 @@ int server::receive_file_data(string fileName) { fileDestination.push_back('/'); fileDestination.append(fileName); - cout << BOLDGREEN << "Criando arquivo " << BOLDYELLOW << fileDestination - << BOLDGREEN << ". Digite novo nome ou enter para continuar: " << RESET; + + cout << BOLDWHITE << "Criando arquivo " << BOLDYELLOW << fileDestination + << BOLDWHITE << ". Digite novo nome ou enter para continuar: " << RESET; string newDestination = ""; getline(cin, newDestination); - if(!newDestination.empty() && newDestination != "\n" ) { fileDestination = newDestination; } - cout << YELLOW << "Criando arquivo: " << fileDestination << "\n" << RESET; - + if (!newDestination.empty() && newDestination != "\n") { + fileDestination = newDestination; + } + cout << YELLOW << "\t--Criando arquivo: " << fileDestination << "--\n" + << RESET; + // Abre o arquivo para escrita ofstream file; file.open(fileDestination, ios::binary); @@ -283,21 +288,19 @@ int server::receive_file_data(string fileName) { int lastSeq = 1; frame *f; - cout << "\tRecebendo dados arquivo\n"; + cout << YELLOW << "\t--Recebendo dados arquivo--\n" << RESET; do { - cout << "Aguardando frame\n"; - // Fica tentando receber um frame f = receive_frame_socket(); if (f == NULL) { - cout << "Erro ao receber dados do arquivo"; + // cout << BOLDRED << "\tErro ao receber dados do arquivo\n" << RESET; + // ->log file.close(); remove(fileDestination.c_str()); return 0; } - cout << "Frame recebido\n"; - f->imprime(HEX); + // f->imprime(HEX); ->log if (f->get_tipo() == FIMT) { break; } @@ -307,24 +310,24 @@ int server::receive_file_data(string fileName) { // Recebeu um frame com uma sequencia errada if (!verify_seq(f->get_seq(), lastSeq)) { - cout << "Frame com a sequencia errada; Pedindo a certa\n"; + // cout << "Frame com a sequencia errada; Pedindo a certa\n"; ->log f->set_seq(lastSeq); send_ack(f); continue; } - if (!verify_crc8(f)) { - cout << "Crc invalido\n"; - continue; + if (!verify_crc8(f)) { + // cout << "Crc invalido\n"; ->log + continue; } - cout << "Seq " << int(f->get_seq()) << "recebida com sucesso\n"; + // cout << "Seq " << int(f->get_seq()) << "recebida com sucesso\n"; ->log lastSeq = f->get_seq(); file.write(f->get_dado(), f->get_tam()); } while (true); - cout << "Dados do arquivo recebido com sucesso\n"; + // cout << "\tDados do arquivo recebido com sucesso\n"; ->log send_ack(f); file.close(); @@ -332,7 +335,8 @@ int server::receive_file_data(string fileName) { } void server::receive_midia(frame *f) { - cout << "Recebendo frame midia\n"; + cout << BOLDYELLOW << "\t--Recebendo arquivo--\n" << RESET; + // cout << "Recebendo frame midia\n"; ->log if (!create_received_dir()) { return; } if (!receive_file_size(f)) { return; } @@ -340,12 +344,12 @@ void server::receive_midia(frame *f) { if (fileName.size() == 0) { return; } - if ( !receive_file_data(fileName) ) { - cout << RED << "\tFalha ao receber o arquivo\n" << RESET; + if (!receive_file_data(fileName)) { + cout << BOLDRED << "\t--Falha ao receber o arquivo\n--" << RESET; return; } - cout << GREEN << "\tArquivo recebido com sucesso\n" << RESET; + cout << BOLDGREEN << "\t--Arquivo recebido com sucesso--\n" << RESET; } // Recebe um frame do cliente @@ -359,7 +363,7 @@ frame *server::receive_frame_socket() { } while (fReceive == NULL && retries < NUM_RETRIES); if (fReceive == NULL && retries == NUM_RETRIES) { - cout << "Desisti de receber o frame\n"; + // cout << "Desisti de receber o frame\n"; ->log return NULL; } @@ -370,8 +374,7 @@ bool server::verify_crc8(frame *f) { int crc8 = f->chk_crc8(); if (!crc8) { send_nack(f); - } - else + } else send_ack(f); return crc8; } @@ -391,7 +394,7 @@ int server::receive_valid_frame(frame **f) { void server::start_receveing_message() { int continueTransmission = 1; - cout << "Recebendo frames\n"; + // cout << "Recebendo frames\n"; ->log frame *f; do { if (!receive_valid_frame(&f)) { return; } @@ -426,14 +429,17 @@ void server::run() { frame *fReceive; if (!(fReceive = socket->receive_frame())) { continue; } - cout << "Frame recebido:" << endl; - fReceive->imprime(HEX); + // cout << "Frame recebido:" << endl; ->log + // fReceive->imprime(HEX); // Verifica se o frame eh de inicio de transmissao e se nao veio com erro int frameType = fReceive->get_tipo(); - if (frameType != INIT) { cout << "Frame ignorado, n eh INIT\n"; continue; } + if (frameType != INIT) { + // cout << "Frame ignorado, n eh INIT\n"; ->log + continue; + } - cout << "Frame de INIT\n"; + // cout << "Frame de INIT\n"; ->log if (!fReceive->chk_crc8()) { send_nack(fReceive); continue; diff --git a/testecor.cpp b/testecor.cpp new file mode 100644 index 0000000..7922883 --- /dev/null +++ b/testecor.cpp @@ -0,0 +1,24 @@ +#include "./headers/cores.h" +#include <iostream> + +int main() { + std::cout << BLACK << "Black\n"; + std::cout << RED << "Red\n"; + std::cout << GREEN << "Green\n"; + std::cout << YELLOW << "Yellow\n"; + std::cout << BLUE << "Blue\n"; + std::cout << MAGENTA << "Magenta\n"; + std::cout << CYAN << "Cyan\n"; + std::cout << WHITE << "White\n"; + std::cout << BOLDBLACK << "Bold Black\n"; + std::cout << BOLDRED << "Bold Red\n"; + std::cout << BOLDGREEN << "Bold Green\n"; + std::cout << BOLDYELLOW << "Bold Yellow\n"; + std::cout << BOLDBLUE << "Bold Blue\n"; + std::cout << BOLDMAGENTA << "Bold Magenta\n"; + std::cout << BOLDCYAN << "Bold Cyan\n"; + std::cout << BOLDWHITE << "Bold White\n"; + std::cout << RESET << "Default\n"; + + return 0; +} \ No newline at end of file diff --git a/todo.txt b/todo.txt index bb047c2..108fd21 100644 --- a/todo.txt +++ b/todo.txt @@ -1,8 +1,8 @@ -> Ver se os frames que estao vindo sao arquivos e juntar eles no arquivo --> Arrumar receive valid frame, retries +-> Fazer send_error --> Arrumar nome arquivo > 63 +-> Arrumar o receive text -> Arrumar a interface -- GitLab