diff --git a/README.md b/README.md index 36a4b9e..f821ed6 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# DevTITANS 05 - HandsOn Linux - Equipe 0X +# DevTITANS 05 - HandsOn Linux - Equipe 06 -Bem-vindo ao repositório da Equipe 0X do HandsON de Linux do DevTITANS! Este projeto contém um firmware para o ESP32 escrito em formato Arduino `.ino`, bem como um driver do kernel Linux escrito em C. O objetivo é demonstrar como criar uma solução completa de hardware e software que integra um dispositivo ESP32 com um sistema Linux. +Bem-vindo ao repositório da Equipe 06 do HandsON de Linux do DevTITANS! Este projeto contém um firmware para o ESP32 escrito em formato Arduino `.ino`, bem como um driver do kernel Linux escrito em C. O objetivo é demonstrar como criar uma solução completa de hardware e software que integra um dispositivo ESP32 com um sistema Linux. ## Tabela de Conteúdos @@ -17,18 +17,19 @@ Bem-vindo ao repositório da Equipe 0X do HandsON de Linux do DevTITANS! Este pr ## Contribuidores - - - - - - +
+ + + + + +
-- **Nome do(a) Aluno(a) 01:** Desenvolvedor do Firmware e Mantenedor do Projeto -- **Nome do(a) Aluno(a) 02:** Desenvolvedor do Firmware -- **Nome do(a) Aluno(a) 03:** Desenvolvedor do Driver Linux -- **Nome do(a) Aluno(a) 04:** Desenvolvedor do Driver Linux -- **Nome do(a) Aluno(a) 05:** Desenvolvedor do Firmware e Escritor da Documentação +- **Cícero Higor** Desenvolvedor do Firmware e Mantenedor do Projeto +- **Enzo Henrique** Desenvolvedor do Firmware e Escritor da Documentação +- **Natalia Rufino** Desenvolvedor do Driver Linux +- **Thaiane Siqueira** Desenvolvedor do Firmware +- **Vinicius Ferreira** Desenvolvedor do Driver Linux ## Introdução @@ -44,7 +45,7 @@ Este projeto serve como um exemplo para desenvolvedores interessados em construi - **Driver do Kernel Linux:** - Rotinas de inicialização e limpeza. - - Operações de arquivo de dispositivo (`GET_LED`, `SET_LED`, `GET_LDR`). + - Operações de arquivo de dispositivo (`GET_LED`, `SET_LED`, `GET_LDR`,`GET_TEMP`,`GET_HUM`). - Comunicação com o ESP32 via Serial. ## Requisitos @@ -54,6 +55,8 @@ Este projeto serve como um exemplo para desenvolvedores interessados em construi - Máquina Linux - Protoboard e Cabos Jumper - Sensor LDR + - LED + - Sensor DHT11 - **Software:** - Arduino IDE @@ -141,4 +144,4 @@ Depois que o driver e o firmware estiverem configurados, você poderá interagir ## Contato -Para perguntas, sugestões ou feedback, entre em contato com o mantenedor do projeto em [maintainer@example.com](mailto:maintainer@example.com). \ No newline at end of file +Para perguntas, sugestões ou feedback, entre em contato com o mantenedor do projeto em [higorgomesousa@gmail.com](higorgomesousa@gmail.com). diff --git a/assets/arduino_serial.png b/assets/arduino_serial.png new file mode 100644 index 0000000..f15f0bf Binary files /dev/null and b/assets/arduino_serial.png differ diff --git a/assets/arduino_serial2.png b/assets/arduino_serial2.png new file mode 100644 index 0000000..d4e7c9c Binary files /dev/null and b/assets/arduino_serial2.png differ diff --git a/assets/cartao01.png b/assets/cartao01.png new file mode 100644 index 0000000..5e7e112 Binary files /dev/null and b/assets/cartao01.png differ diff --git a/assets/cartao2.jpg b/assets/cartao2.jpg new file mode 100644 index 0000000..2169a29 Binary files /dev/null and b/assets/cartao2.jpg differ diff --git a/assets/cartao3.jpg b/assets/cartao3.jpg new file mode 100644 index 0000000..bad93ba Binary files /dev/null and b/assets/cartao3.jpg differ diff --git a/assets/cartao4.png b/assets/cartao4.png new file mode 100644 index 0000000..e3c8c64 Binary files /dev/null and b/assets/cartao4.png differ diff --git a/assets/cartao5.JPG b/assets/cartao5.JPG new file mode 100644 index 0000000..670e0ab Binary files /dev/null and b/assets/cartao5.JPG differ diff --git a/assets/montagem1.jpg b/assets/montagem1.jpg new file mode 100644 index 0000000..9dcdb63 Binary files /dev/null and b/assets/montagem1.jpg differ diff --git a/assets/montagem2.jpg b/assets/montagem2.jpg new file mode 100644 index 0000000..33342a6 Binary files /dev/null and b/assets/montagem2.jpg differ diff --git a/esp32/montagem.jpg b/esp32/montagem.jpg new file mode 100644 index 0000000..9dcdb63 Binary files /dev/null and b/esp32/montagem.jpg differ diff --git a/esp32/pinos.txt b/esp32/pinos.txt index e69de29..9f8071c 100644 --- a/esp32/pinos.txt +++ b/esp32/pinos.txt @@ -0,0 +1,5 @@ +1 - Montagem do Protótipo ESP32. Para os pinos usamos: +PINO_LED = 23 +PINO_LDR = 33 +PINO_DHT = 26 + diff --git a/smartlamp-kernel-module/Makefile b/smartlamp-kernel-module/Makefile index be05f47..9bc1a6a 100644 --- a/smartlamp-kernel-module/Makefile +++ b/smartlamp-kernel-module/Makefile @@ -1,7 +1,7 @@ -obj-m += SUBISTITUA_PELO_NOME_DO_MODULO.o +obj-m += probe.o serial.o serial_write.o smartlamp.o #sysfs.o PWD := $(CURDIR) all: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules clean: - make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean \ No newline at end of file + make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean diff --git a/smartlamp-kernel-module/led b/smartlamp-kernel-module/led new file mode 100644 index 0000000..29d6383 --- /dev/null +++ b/smartlamp-kernel-module/led @@ -0,0 +1 @@ +100 diff --git a/smartlamp-kernel-module/probe.c b/smartlamp-kernel-module/probe.c index 7374e5c..f92de98 100644 --- a/smartlamp-kernel-module/probe.c +++ b/smartlamp-kernel-module/probe.c @@ -14,8 +14,8 @@ static uint usb_in, usb_out; // Endereços das portas de e static char *usb_in_buffer, *usb_out_buffer; // Buffers de entrada e saída da USB static int usb_max_size; // Tamanho máximo de uma mensagem USB -#define VENDOR_ID SUBSTITUA_PELO_VENDORID /* Encontre o VendorID do smartlamp */ -#define PRODUCT_ID SUBSTITUA_PELO_PRODUCTID /* Encontre o ProductID do smartlamp */ +#define VENDOR_ID 0x10c4 /* Encontre o VendorID do smartlamp */ +#define PRODUCT_ID 0xea60 /* Encontre o ProductID do smartlamp */ static const struct usb_device_id id_table[] = { { USB_DEVICE(VENDOR_ID, PRODUCT_ID) }, {} }; static int usb_probe(struct usb_interface *ifce, const struct usb_device_id *id); // Executado quando o dispositivo é conectado na USB @@ -56,4 +56,4 @@ static void usb_disconnect(struct usb_interface *interface) { printk(KERN_INFO "SmartLamp: Dispositivo desconectado.\n"); kfree(usb_in_buffer); // Desaloca buffers kfree(usb_out_buffer); -} \ No newline at end of file +} diff --git a/smartlamp-kernel-module/serial.c b/smartlamp-kernel-module/serial.c index fe2b79a..dba6f41 100644 --- a/smartlamp-kernel-module/serial.c +++ b/smartlamp-kernel-module/serial.c @@ -15,8 +15,8 @@ static uint usb_in, usb_out; // Endereços das portas de e static char *usb_in_buffer, *usb_out_buffer; // Buffers de entrada e saída da USB static int usb_max_size; // Tamanho máximo de uma mensagem USB -#define VENDOR_ID SUBSTITUA_PELO_VENDORID /* Encontre o VendorID do smartlamp */ -#define PRODUCT_ID SUBSTITUA_PELO_PRODUCTID /* Encontre o ProductID do smartlamp */ +#define VENDOR_ID 0x10c4 /* Encontre o VendorID do smartlamp */ +#define PRODUCT_ID 0xea60 /* Encontre o ProductID do smartlamp */ static const struct usb_device_id id_table[] = { { USB_DEVICE(VENDOR_ID, PRODUCT_ID) }, {} }; static int usb_probe(struct usb_interface *ifce, const struct usb_device_id *id); // Executado quando o dispositivo é conectado na USB @@ -74,16 +74,33 @@ static int usb_read_serial() { // Lê os dados da porta serial e armazena em usb_in_buffer // usb_in_buffer - contem a resposta em string do dispositivo // actual_size - contem o tamanho da resposta em bytes + strcpy(usb_out_buffer,"GET_LDR"); + ret = usb_bulk_msg(smartlamp_device, usb_sndbulkpipe(smartlamp_device, usb_out), usb_out_buffer, strlen("GET_LDR"), &actual_size, 1000); + + if(ret){ + continue; + } + ret = usb_bulk_msg(smartlamp_device, usb_rcvbulkpipe(smartlamp_device, usb_in), usb_in_buffer, min(usb_max_size, MAX_RECV_LINE), &actual_size, 1000); if (ret) { printk(KERN_ERR "SmartLamp: Erro ao ler dados da USB (tentativa %d). Codigo: %d\n", ret, retries--); + printk("%s", usb_in_buffer); continue; } - + else{ + printk("%s", usb_in_buffer); + int value = 0 ; + int i = 0 ; + for(i = 0; i < 4; i++){ + //printk("%d", (int)usb_in_buffer[actual_size -4 + i] -48); + value = (value * 10) + ((int)usb_in_buffer[actual_size -4 + i] -48); + } + return value; + } //caso tenha recebido a mensagem 'RES_LDR X' via serial acesse o buffer 'usb_in_buffer' e retorne apenas o valor da resposta X //retorne o valor de X em inteiro return 0; } return -1; -} \ No newline at end of file +} diff --git a/smartlamp-kernel-module/serial_write.c b/smartlamp-kernel-module/serial_write.c index 41e4e79..da0b7a3 100644 --- a/smartlamp-kernel-module/serial_write.c +++ b/smartlamp-kernel-module/serial_write.c @@ -15,13 +15,14 @@ static uint usb_in, usb_out; // Endereços das portas de e static char *usb_in_buffer, *usb_out_buffer; // Buffers de entrada e saída da USB static int usb_max_size; // Tamanho máximo de uma mensagem USB -#define VENDOR_ID SUBSTITUA_PELO_VENDORID /* Encontre o VendorID do smartlamp */ -#define PRODUCT_ID SUBSTITUA_PELO_PRODUCTID /* Encontre o ProductID do smartlamp */ +#define VENDOR_ID 0x10c4 /* Encontre o VendorID do smartlamp */ +#define PRODUCT_ID 0xea60 /* Encontre o ProductID do smartlamp */ static const struct usb_device_id id_table[] = { { USB_DEVICE(VENDOR_ID, PRODUCT_ID) }, {} }; static int usb_probe(struct usb_interface *ifce, const struct usb_device_id *id); // Executado quando o dispositivo é conectado na USB static void usb_disconnect(struct usb_interface *ifce); // Executado quando o dispositivo USB é desconectado da USB static int usb_read_serial(void); // Executado para ler a saida da porta serial +static int usb_write_serial(char *cmd, int param); MODULE_DEVICE_TABLE(usb, id_table); bool ignore = true; @@ -52,7 +53,7 @@ static int usb_probe(struct usb_interface *interface, const struct usb_device_id usb_out_buffer = kmalloc(usb_max_size, GFP_KERNEL); - usb_write_serial(COMANDO_SMARTLAMP, VALOR); + usb_write_serial("SET_LED", 100); printk("LDR Value: %d\n", LDR_value); @@ -69,11 +70,19 @@ static void usb_disconnect(struct usb_interface *interface) { static int usb_write_serial(char *cmd, int param) { int ret, actual_size; char resp_expected[MAX_RECV_LINE]; // Resposta esperada do comando - + char buffer[3]; // use a variavel usb_out_buffer para armazernar o comando em formato de texto que o firmware reconheça + strcpy(usb_out_buffer,cmd); + strcat(usb_out_buffer, " "); + sprintf(buffer,"%d", param); + strcat(usb_out_buffer, buffer); +/* ret = usb_bulk_msg(smartlamp_device, usb_sndbulkpipe(smartlamp_device, usb_out), usb_out_buffer, strlen(usb_out_buffer), &actual_size, 1000); + if(ret){ + continue; + }*/ // Grave o valor de usb_out_buffer com printk - + printk("%s \n",usb_out_buffer); // Envie o comando pela porta Serial ret = usb_bulk_msg(smartlamp_device, usb_sndbulkpipe(smartlamp_device, usb_out), usb_out_buffer, strlen(usb_out_buffer), &actual_size, 1000*HZ); if (ret) { @@ -86,4 +95,4 @@ static int usb_write_serial(char *cmd, int param) { sprintf(resp_expected, "RES %s", cmd); return -1; -} \ No newline at end of file +} diff --git a/smartlamp-kernel-module/smartlamp.c b/smartlamp-kernel-module/smartlamp.c index 91362ca..fa34bc8 100644 --- a/smartlamp-kernel-module/smartlamp.c +++ b/smartlamp-kernel-module/smartlamp.c @@ -1,6 +1,7 @@ #include #include #include +#include MODULE_AUTHOR("DevTITANS "); MODULE_DESCRIPTION("Driver de acesso ao SmartLamp (ESP32 com Chip Serial CP2102"); @@ -16,13 +17,14 @@ static uint usb_in, usb_out; // Endereços das portas de e static char *usb_in_buffer, *usb_out_buffer; // Buffers de entrada e saída da USB static int usb_max_size; // Tamanho máximo de uma mensagem USB -#define VENDOR_ID SUBSTITUA_PELO_VENDORID /* Encontre o VendorID do smartlamp */ -#define PRODUCT_ID SUBSTITUA_PELO_PRODUCTID /* Encontre o ProductID do smartlamp */ +#define VENDOR_ID 0x10c4 /* Encontre o VendorID do smartlamp */ +#define PRODUCT_ID 0xea60 /* Encontre o ProductID do smartlamp */ static const struct usb_device_id id_table[] = { { USB_DEVICE(VENDOR_ID, PRODUCT_ID) }, {} }; static int usb_probe(struct usb_interface *ifce, const struct usb_device_id *id); // Executado quando o dispositivo é conectado na USB static void usb_disconnect(struct usb_interface *ifce); // Executado quando o dispositivo USB é desconectado da USB -static int usb_read_serial(void); +//static int usb_read_serial(void); +static int usb_send_cmd(char *cmd, int param); // Executado quando o arquivo /sys/kernel/smartlamp/{led, ldr} é lido (e.g., cat /sys/kernel/smartlamp/led) static ssize_t attr_show(struct kobject *sys_obj, struct kobj_attribute *attr, char *buff); @@ -55,7 +57,7 @@ static int usb_probe(struct usb_interface *interface, const struct usb_device_id printk(KERN_INFO "SmartLamp: Dispositivo conectado ...\n"); - // Cria arquivos do /sys/kernel/smartlamp/* + // Cria arquivos do /sys/kernel/smartlamp sys_obj = kobject_create_and_add("smartlamp", kernel_kobj); ignore = sysfs_create_group(sys_obj, &attr_group); // AQUI @@ -68,9 +70,11 @@ static int usb_probe(struct usb_interface *interface, const struct usb_device_id usb_in_buffer = kmalloc(usb_max_size, GFP_KERNEL); usb_out_buffer = kmalloc(usb_max_size, GFP_KERNEL); - LDR_value = usb_read_serial(); - - printk("LDR Value: %d\n", LDR_value); + // msleep(2000); +// LDR_value = usb_read_serial(); + printk("LDR Value: %d\n",usb_send_cmd("GET_LDR", -1)); + msleep(2000); + printk("SET Value: %d\n", usb_send_cmd("SET_LED",0)); return 0; } @@ -98,10 +102,16 @@ static int usb_send_cmd(char *cmd, int param) { printk(KERN_INFO "SmartLamp: Enviando comando: %s\n", cmd); // preencha o buffer // Caso contrário, é só o comando mesmo - + strcpy(usb_out_buffer,cmd); + if(param != -1){ + char buffer[3]; + strcat(usb_out_buffer, " "); + sprintf(buffer,"%d", param); + strcat(usb_out_buffer, buffer); + } // Envia o comando (usb_out_buffer) para a USB // Procure a documentação da função usb_bulk_msg para entender os parâmetros - ret = usb_bulk_msg(smartlamp_device, usb_sndbulkpipe(smartlamp_device, usb_out), BUFFER, ?, &actual_size, 1000); + ret = usb_bulk_msg(smartlamp_device, usb_sndbulkpipe(smartlamp_device, usb_out), usb_out_buffer, strlen(usb_out_buffer), &actual_size, 2000); if (ret) { printk(KERN_ERR "SmartLamp: Erro de codigo %d ao enviar comando!\n", ret); return -1; @@ -112,12 +122,48 @@ static int usb_send_cmd(char *cmd, int param) { // Espera pela resposta correta do dispositivo (desiste depois de várias tentativas) while (retries > 0) { // Lê dados da USB - ret = usb_bulk_msg(smartlamp_device, usb_rcvbulkpipe(smartlamp_device, usb_in), usb_in_buffer, min(usb_max_size, MAX_RECV_LINE), &actual_size, 1000); + ret = usb_bulk_msg(smartlamp_device, usb_rcvbulkpipe(smartlamp_device, usb_in), usb_in_buffer, min(usb_max_size, MAX_RECV_LINE), &actual_size, 2000); if (ret) { printk(KERN_ERR "SmartLamp: Erro ao ler dados da USB (tentativa %d). Codigo: %d\n", ret, retries--); continue; } + + //int value[5] ; + int value = 0; + int value1 = 0 ; +// char *str_value = kmalloc(usb_max_size, GFP_KERNEL); ; + int i = strlen(usb_in_buffer) ; + int j = i; +// char j = ' '; +// int k = 0; + //printk("%s", usb_in_buffer); + if(strcmp(usb_in_buffer,resp_expected) > 0){ + //printk("AQUI"); + printk("%s", usb_in_buffer); + //for(i = 0; i < strlen(usb_in_buffer); i++){ + //while(strcmp(usb_in_buffer[i]," ") != 0){ + while(usb_in_buffer[i] != ' '){ + //printk("%d", (int)usb_in_buffer[actual_size -4 + i] -48); + //value = ((int)usb_in_buffer[i-2] - 48); + //strcat(str_value,usb_in_buffer[i-2]); + ///value = usb_in_buffer[i-2]; + //strcat(str_value, &usb_in_buffer[i-2]); + //printk("%c",value); + i--; + } + i++; + while(i < (j-1)){ + //printk("%d",usb_in_buffer[i] - 48); + if(((int)usb_in_buffer[i] -48)>=0){ + value = (value*10) + ((int)usb_in_buffer[i] -48); + } + i++; + } + //printk("%d",value); + return value; + } + // adicione a sua implementação do médodo usb_read_serial } return -1; // Não recebi a resposta esperada do dispositivo @@ -126,14 +172,33 @@ static int usb_send_cmd(char *cmd, int param) { // Executado quando o arquivo /sys/kernel/smartlamp/{led, ldr} é lido (e.g., cat /sys/kernel/smartlamp/led) static ssize_t attr_show(struct kobject *sys_obj, struct kobj_attribute *attr, char *buff) { // value representa o valor do led ou ldr - int value; + //int value; // attr_name representa o nome do arquivo que está sendo lido (ldr ou led) - const char *attr_name = attr->attr.name; + //const char *attr_name = attr->attr.name; + + int value = 0; // variável usada para armazenar o valor lido do dispositivo + const char *attr_name = attr->attr.name; // obtém o nome do atributo que está sendo lido do objeto attr + int ret; // usada para armazenar o resultado das chamadas da funcao usb_send_cmd // printk indicando qual arquivo está sendo lido - printk(KERN_INFO "SmartLamp: Lendo %s ...\n", attr_name); + printk(KERN_INFO "SmartLamp: Lendo %s ...\n", attr_name); // Implemente a leitura do valor do led ou ldr usando a função usb_send_cmd() + if (strcmp(attr_name, "led") == 0) { + // Leitura do LED + ret = usb_send_cmd("GET_LED", -1); // chama a função usb_send_cmd para enviar o comando GET_LED + } else if (strcmp(attr_name, "ldr") == 0) { + // Leitura do LDR + ret = usb_send_cmd("GET_LDR", -1); // chama a função usb_send_cmd para enviar o comando GET_LDR + } else { + printk(KERN_ALERT "SmartLamp: Atributo desconhecido %s.\n", attr_name); + return -ENODEV; + } + + if (ret < 0) { + printk(KERN_ALERT "SmartLamp: Erro ao ler %s.\n", attr_name); // Verifica se houve um erro ao enviar o comando USB (retornado por usb_send_cmd + return ret; + } sprintf(buff, "%d\n", value); // Cria a mensagem com o valor do led, ldr return strlen(buff); @@ -152,10 +217,14 @@ static ssize_t attr_store(struct kobject *sys_obj, struct kobj_attribute *attr, printk(KERN_ALERT "SmartLamp: valor de %s invalido.\n", attr_name); return -EACCES; } - - printk(KERN_INFO "SmartLamp: Setando %s para %ld ...\n", attr_name, value); - - // utilize a função usb_send_cmd para enviar o comando SET_LED X + // utilize a função usb_send_cmd para enviar o comando SET_LED + if (strcmp(attr_name, "ldr") == 0) { + printk(KERN_ALERT "SmartLamp: escrita no arquivo LDR não permitida.\n"); + return -EACCES; // Retorna erro ao tentar escrever no arquivo LDR + } else if (strcmp(attr_name, "led") == 0) { + printk(KERN_INFO "SmartLamp: Setando %s para %ld ...\n", attr_name, value); + usb_send_cmd("SET_LED ", value); + } if (ret < 0) { printk(KERN_ALERT "SmartLamp: erro ao setar o valor do %s.\n", attr_name); @@ -163,4 +232,4 @@ static ssize_t attr_store(struct kobject *sys_obj, struct kobj_attribute *attr, } return strlen(buff); -} \ No newline at end of file +} diff --git a/smartlamp-kernel-module/sysfs.c b/smartlamp-kernel-module/sysfs.c index 385d5db..f8ef914 100644 --- a/smartlamp-kernel-module/sysfs.c +++ b/smartlamp-kernel-module/sysfs.c @@ -15,8 +15,8 @@ static uint usb_in, usb_out; // Endereços das portas de e static char *usb_in_buffer, *usb_out_buffer; // Buffers de entrada e saída da USB static int usb_max_size; // Tamanho máximo de uma mensagem USB -#define VENDOR_ID SUBSTITUA_PELO_VENDORID /* Encontre o VendorID do smartlamp */ -#define PRODUCT_ID SUBSTITUA_PELO_PRODUCTID /* Encontre o ProductID do smartlamp */ +#define VENDOR_ID 0x10c4 /* Encontre o VendorID do smartlamp */ +#define PRODUCT_ID 0xea60 /* Encontre o ProductID do smartlamp */ static const struct usb_device_id id_table[] = { { USB_DEVICE(VENDOR_ID, PRODUCT_ID) }, {} }; static int usb_probe(struct usb_interface *ifce, const struct usb_device_id *id); // Executado quando o dispositivo é conectado na USB @@ -79,6 +79,7 @@ static int usb_probe(struct usb_interface *interface, const struct usb_device_id static void usb_disconnect(struct usb_interface *interface) { printk(KERN_INFO "SmartLamp: Dispositivo desconectado.\n"); if (sys_obj) kobject_put(sys_obj); // Remove os arquivos em /sys/kernel/smartlamp + kfree(usb_in_buffer); // Desaloca buffers kfree(usb_out_buffer); } @@ -97,7 +98,17 @@ static int usb_read_serial() { printk(KERN_ERR "SmartLamp: Erro ao ler dados da USB (tentativa %d). Codigo: %d\n", ret, retries--); continue; } - + else{ + printk("%s", usb_in_buffer); + int value = 0 ; + int i = 0 ; + //for(i = 0; i < 4; i++){ + for(i = 0; i <= (actual_size-12); i++){ + //printk("%d", (int)usb_in_buffer[actual_size -4 + i] -48); + value = (value * 10) + ((int)usb_in_buffer[12 + i] -48); + } + return value; + } //caso tenha recebido a mensagem 'RES_LDR X' via serial acesse o buffer 'usb_in_buffer' e retorne apenas o valor da resposta X //retorne o valor de X em inteiro return 0; @@ -109,7 +120,9 @@ static int usb_read_serial() { // Executado quando o arquivo /sys/kernel/smartlamp/{led, ldr} é lido (e.g., cat /sys/kernel/smartlamp/led) static ssize_t attr_show(struct kobject *sys_obj, struct kobj_attribute *attr, char *buff) { // value representa o valor do led ou ldr - int value = -1; + + long value; + int ret, actual_size; // attr_name representa o nome do arquivo que está sendo lido (ldr ou led) const char *attr_name = attr->attr.name; @@ -117,9 +130,30 @@ static ssize_t attr_show(struct kobject *sys_obj, struct kobj_attribute *attr, c printk(KERN_INFO "SmartLamp: Lendo %s ...\n", attr_name); // Implemente a leitura do valor do led usando a função usb_read_serial() - + if (strcmp(attr_name, "led") == 0) { + // Exibe seu nome quando o arquivo led é lido + printk(KERN_INFO "SmartLamp: Natalia"); + } else if (strcmp(attr_name, "ldr") == 0) { + // Exibe "DevTITANS" quando o arquivo ldr é lido + printk(KERN_INFO "SmartLamp: DevTITANS\n"); + } else { + // Se outro arquivo for lido, exibe uma mensagem de erro + printk(KERN_ERR "SmartLamp: Arquivo desconhecido: %s\n", attr_name); + return -EACCES; + } + if(attr_name == "ldr"){ + strcpy(usb_out_buffer,"GET_LDR"); + } else{ + strcpy(usb_out_buffer,"GET_LED"); + } + ret = usb_bulk_msg(smartlamp_device, usb_sndbulkpipe(smartlamp_device, usb_out), usb_out_buffer, strlen("GET_LDR"), &actual_size, 1000); - sprintf(buff, "%d\n", value); // Cria a mensagem com o valor do led, ldr + if(ret){ + return -1; + } + value = usb_read_serial(); + + //sprintf(buff, "%d\n", value); // Cria a mensagem com o valor do led, ldr return strlen(buff); } @@ -137,12 +171,12 @@ static ssize_t attr_store(struct kobject *sys_obj, struct kobj_attribute *attr, return -EACCES; } - printk(KERN_INFO "SmartLamp: Setando %s para %ld ...\n", attr_name, value); - - if (ret < 0) { - printk(KERN_ALERT "SmartLamp: erro ao setar o valor do %s.\n", attr_name); - return -EACCES; + // Verifica o nome do atributo e executa ações específicas + if (strcmp(attr_name, "ldr") == 0) { + printk(KERN_ALERT "SmartLamp: escrita no arquivo LDR não permitida.\n"); + return -EACCES; // Retorna erro ao tentar escrever no arquivo LDR + } else if (strcmp(attr_name, "led") == 0) { + printk(KERN_INFO "SmartLamp: valor recebido para led é %ld.\n", value); } - return strlen(buff); -} \ No newline at end of file +} diff --git a/smartlamp.ino b/smartlamp.ino deleted file mode 100644 index 62349a3..0000000 --- a/smartlamp.ino +++ /dev/null @@ -1,44 +0,0 @@ -// Defina os pinos de LED e LDR -// Defina uma variável com valor máximo do LDR (4000) -// Defina uma variável para guardar o valor atual do LED (10) -int ledPin; -int ledValue; - -int ldrPin; -// Faça testes no sensor ldr para encontrar o valor maximo e atribua a variável ldrMax -int ldrMax; - -void setup() { - Serial.begin(9600); - - pinMode(ledPin, OUTPUT); - pinMode(ldrPin, INPUT); - - Serial.printf("SmartLamp Initialized.\n"); - - -} - -// Função loop será executada infinitamente pelo ESP32 -void loop() { - //Obtenha os comandos enviados pela serial - //e processe-os com a função processCommand -} - - -void processCommand(String command) { - // compare o comando com os comandos possíveis e execute a ação correspondente -} - -// Função para atualizar o valor do LED -void ledUpdate() { - // Valor deve convertar o valor recebido pelo comando SET_LED para 0 e 255 - // Normalize o valor do LED antes de enviar para a porta correspondente -} - -// Função para ler o valor do LDR -int ldrGetValue() { - // Leia o sensor LDR e retorne o valor normalizado entre 0 e 100 - // faça testes para encontrar o valor maximo do ldr (exemplo: aponte a lanterna do celular para o sensor) - // Atribua o valor para a variável ldrMax e utilize esse valor para a normalização -} \ No newline at end of file diff --git a/smartlamp/smartlamp.ino b/smartlamp/smartlamp.ino new file mode 100644 index 0000000..608a6bd --- /dev/null +++ b/smartlamp/smartlamp.ino @@ -0,0 +1,154 @@ +// Defina os pinos de LED e LDR +// Defina uma variável com valor máximo do LDR (4000) +// Defina uma variável para guardar o valor atual do LED (10) +#include +#include + + +/* + https://gist.github.com/aferreira44/6bbe8fab792e24afc6c1389da714aa99 + https://embarcados.com.br/como-programar-o-esp32-na-arduino-ide/ + https://kb.deec.uc.pt/books/deec/page/programa-led-a-piscar + https://portal.vidadesilicio.com.br/led-com-esp32-curso-esp32-basico/ + https://portal.vidadesilicio.com.br/como-utilizar-o-led-rgb-com-arduino/ + https://www.paulotrentin.com.br/programacao/dicas/lendo-uma-string-com-arduino-via-serial/ + https://www.youtube.com/watch?v=GDxwDsphyuk&ab_channel=BrincandocomIdeias + https://blogmasterwalkershop.com.br/arduino/arduino-exibindo-e-lendo-dados-da-serial + https://forum.arduino.cc/t/test-if-a-string-contains-a-string/478927/4 + https://www.blogdarobotica.com/2022/06/30/controlando-o-brilho-do-led-usando-potenciometro-e-arduino/ + https://www.tutorialspoint.com/find-if-a-substring-exists-within-a-string-in-arduino#:~:text=In%20order%20to%20check%20if,searching%20for%20within%20another%20string. + https://forum.arduino.cc/t/duvida-com-substring/1045145 + https://www.clubedohardware.com.br/forums/topic/1360900-como-utilizar-o-parseint-arduino/ + sudo chmod a+rw /dev/ttyUSB0 + +*/ + +int PINO_DHT = 26; + +int PINO_LED = 23; +int PINO_LDR = 33; +int ledValue = 10; +int ldrMax; +DHT dht(PINO_DHT, DHT11); + +void setup() { + pinMode(PINO_LED, OUTPUT); + pinMode(PINO_LDR, INPUT); + pinMode(PINO_DHT, INPUT); + analogWrite(PINO_LED,ledValue); + Serial.begin(9600); + dht.begin(); + //processCommand("GET_LDR"); +} + +void loop() { + // Se receber algo pela serial + if (Serial.available() > 0) { + // Lê toda string recebida + String teclado = leStringSerial(); + // chama a funcao de processar string para comando no circuito + processCommand(teclado); + } +} + + +void processCommand(String command) { + // Verifica se o comando passado contém SET_LED e apos o espaco seja um valor numericoó + String valorAposComando = command.substring(8, command.length()); + if (command.indexOf("SET_LED ") >= 0 && isNumero(valorAposComando)) { + //caso seja verdadeiro, transforma o valor da string após o espaco + ledValue = valorAposComando.toInt(); + //verifica se esse valor esta no range de 0 a 100 + if (ledValue >= 0 && ledValue <= 100 ) { + // valor maior que 0 , liga led + if (ledValue > 0 ) { + ledUpdate(); + Serial.println("RES SET_LED 1"); + } else { + // valor igual a 0 desliga o led + ledUpdate(); + Serial.println("RES SET_LED 1"); + } + + } else + Serial.println("RES SET_LED-1"); + // caso o range passado seja invalido + + } else if (command.indexOf("GET_LED") >= 0) + // retorna o valor do led atual + Serial.printf("RES GET_LED %d\n", ledGetValue()); + else if (command.indexOf("GET_LDR") >= 0) + Serial.printf("RES GET_LDR %d\n", ldrGetValue()); + else if (command.indexOf("GET_TEMP") >= 0){ + float temperatura = dht.readTemperature(); + Serial.printf("RES GET_TEMP %2.f\n", temperatura); + }else if (command.indexOf("GET_HUM") >= 0){ + float umidade = dht.readHumidity(); + Serial.printf("RES GET_HUM %2.f\n", umidade); + } + else + Serial.println("ERR Unknown command."); + +} + + +// Função para atualizar o valor do LED +void ledUpdate() { + // Normalize o valor do LED antes de enviar para a porta correspondente + int val = map(ledValue, 0, 1023, 0, 255); +// val = map(ledValue, 0, 1023, 0, 255); + analogWrite(PINO_LED, val); + +} + + +// Função para ler o valor do LDR +int ldrGetValue() { + int sensorValue = analogRead(PINO_LDR); + return sensorValue; + // Leia o sensor LDR e retorne o valor normalizado + +} + + + +// Função para ler o valor do LED +int ledGetValue() { + return ledValue; +} + + + +/** + Função que lê uma string da Serial +*/ + +String leStringSerial() { + String conteudo = ""; + char caractere; + // Enquanto receber algo pela serial + while (Serial.available() > 0) { + // Lê byte da serial + caractere = Serial.read(); + // Ignora caractere de quebra de linha + if (caractere != '\n') { + // Concatena valores + conteudo.concat(caractere); + } + // Aguarda buffer serial ler próximo caractere + delay(20); + } + return conteudo; +} + + + +bool isNumero(String str) { + + for (int i = 0; i < str.length(); i++) { + if (!isdigit(str.charAt(i))) + return false; + } + return true; + +}