diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..413ac2d --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +.vscode/ +*.cmd +*.symvers +*.order +*.ko +*.mod +*.o +*.mod.c diff --git a/smartlamp-kernel-module/Makefile b/smartlamp-kernel-module/Makefile index be05f47..b0415ad 100644 --- a/smartlamp-kernel-module/Makefile +++ b/smartlamp-kernel-module/Makefile @@ -1,4 +1,4 @@ -obj-m += SUBISTITUA_PELO_NOME_DO_MODULO.o +obj-m += sysfs.o PWD := $(CURDIR) all: diff --git a/smartlamp-kernel-module/probe.c b/smartlamp-kernel-module/probe.c index 7374e5c..c9c9097 100644 --- a/smartlamp-kernel-module/probe.c +++ b/smartlamp-kernel-module/probe.c @@ -14,8 +14,9 @@ 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 // Vendor ID smartlamp +#define PRODUCT_ID 0xea60 // Product ID 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 diff --git a/smartlamp-kernel-module/serial.c b/smartlamp-kernel-module/serial.c index fe2b79a..c916f06 100644 --- a/smartlamp-kernel-module/serial.c +++ b/smartlamp-kernel-module/serial.c @@ -1,22 +1,23 @@ #include #include #include +#include // Para usar a função strncmp +#include // Para usar a função min +#include // Para usar a função isdigit MODULE_AUTHOR("DevTITANS "); MODULE_DESCRIPTION("Driver de acesso ao SmartLamp (ESP32 com Chip Serial CP2102"); MODULE_LICENSE("GPL"); - #define MAX_RECV_LINE 100 // Tamanho máximo de uma linha de resposta do dispositvo USB - static struct usb_device *smartlamp_device; // Referência para o dispositivo USB static uint usb_in, usb_out; // Endereços das portas de entrada e saida da USB 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 /* Substitua pelo VendorID do SmartLamp */ +#define PRODUCT_ID 0xea60 /* Substitua pelo 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 @@ -39,22 +40,21 @@ module_usb_driver(smartlamp_driver); // Executado quando o dispositivo é conectado na USB static int usb_probe(struct usb_interface *interface, const struct usb_device_id *id) { struct usb_endpoint_descriptor *usb_endpoint_in, *usb_endpoint_out; - printk(KERN_INFO "SmartLamp: Dispositivo conectado ...\n"); - // Detecta portas e aloca buffers de entrada e saída de dados na USB smartlamp_device = interface_to_usbdev(interface); - ignore = usb_find_common_endpoints(interface->cur_altsetting, &usb_endpoint_in, &usb_endpoint_out, NULL, NULL); // AQUI + ignore = usb_find_common_endpoints(interface->cur_altsetting, &usb_endpoint_in, &usb_endpoint_out, NULL, NULL); // AQUI + if (ignore) { + printk(KERN_ERR "SmartLamp: Falha ao encontrar endpoints\n"); + return -ENODEV; + } usb_max_size = usb_endpoint_maxp(usb_endpoint_in); usb_in = usb_endpoint_in->bEndpointAddress; usb_out = usb_endpoint_out->bEndpointAddress; 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); - + printk(KERN_INFO "SmartLamp: LDR Value: %d\n", LDR_value); return 0; } @@ -67,23 +67,29 @@ static void usb_disconnect(struct usb_interface *interface) { static int usb_read_serial() { int ret, actual_size; - int retries = 10; // Tenta algumas vezes receber uma resposta da USB. Depois desiste. - + int retries = 10; // Tenta algumas vezes receber uma resposta da USB. Depois desiste. + char *response_prefix = "RES GET_LDR "; + int response_prefix_len = strlen(response_prefix); + int ldr_value = -1; // Espera pela resposta correta do dispositivo (desiste depois de várias tentativas) while (retries > 0) { // 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 - 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) { + // usb_in_buffer - contem a resposta em string do dispositivo + // actual_size - contem o tamanho da resposta em bytes + ret = usb_bulk_msg(smartlamp_device, usb_rcvbulkpipe(smartlamp_device, usb_in), usb_in_buffer, min(usb_max_size, MAX_RECV_LINE), &actual_size, 5000); + if (ret) { printk(KERN_ERR "SmartLamp: Erro ao ler dados da USB (tentativa %d). Codigo: %d\n", ret, retries--); continue; } - - //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; + usb_in_buffer[actual_size] = '\0'; // Assegura que o buffer está terminado em null + printk(KERN_INFO "SmartLamp: Dados recebidos: %s\n", usb_in_buffer); + // Verifica se a resposta começa com "RES GET_LDR " + if (strncmp(usb_in_buffer, response_prefix, response_prefix_len) == 0) { + // Extrai o valor após o prefixo + ldr_value = simple_strtol(usb_in_buffer + response_prefix_len, NULL, 10); + printk(KERN_INFO "SmartLamp: LDR Value recebido: %d\n", ldr_value); + return ldr_value; + } } - - return -1; + return -1; } \ No newline at end of file diff --git a/smartlamp-kernel-module/sysfs.c b/smartlamp-kernel-module/sysfs.c index 9f69c66..e044845 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 @@ -80,6 +80,7 @@ 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); + kobject_put(sys_obj); } static int usb_read_serial() { @@ -116,6 +117,13 @@ 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("led", attr_name) == 0){ + pr_info("SmartLamp: João Danilo\n"); + } + else if(strcmp("ldr", attr_name) == 0){ + pr_info("SmartLamp: DevTITANS\n"); + } sprintf(buff, "%d\n", value); // Cria a mensagem com o valor do led, ldr @@ -138,6 +146,14 @@ static ssize_t attr_store(struct kobject *sys_obj, struct kobj_attribute *attr, printk(KERN_INFO "SmartLamp: Setando %s para %ld ...\n", attr_name, value); + if(strcmp("led", attr_name) == 0){ + pr_info("SmartLamp: O valor passado foi %ld\n", value); + } + else if(strcmp("ldr", attr_name) == 0){ + pr_err("SmartLamp: Erro ao enviar comando ao LDR\n"); + ret = -1; + } + if (ret < 0) { printk(KERN_ALERT "SmartLamp: erro ao setar o valor do %s.\n", attr_name); return -EACCES; diff --git a/smartlamp.ino b/smartlamp.ino index 62349a3..212a502 100644 --- a/smartlamp.ino +++ b/smartlamp.ino @@ -1,44 +1,60 @@ // 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 ledPin = 25; int ledValue; - -int ldrPin; +int ldrPin = A0; // Faça testes no sensor ldr para encontrar o valor maximo e atribua a variável ldrMax -int ldrMax; +int ldrMax = 4000; void setup() { Serial.begin(9600); - pinMode(ledPin, OUTPUT); pinMode(ldrPin, INPUT); - Serial.printf("SmartLamp Initialized.\n"); - - + delay(8000); + processCommand(String("GET_LDR")); } - // Função loop será executada infinitamente pelo ESP32 void loop() { //Obtenha os comandos enviados pela serial //e processe-os com a função processCommand + if (Serial.available() > 0) { + String str = Serial.readString(); + str.trim(); + processCommand(str); + } } - - void processCommand(String command) { // compare o comando com os comandos possíveis e execute a ação correspondente + if (command.equals(String("GET_LDR"))) { + Serial.printf("RES GET_LDR %d\n", ldrGetValue()); + } else if (command.equals(String("GET_LED"))) { + Serial.printf("RES GET_LED %d\n", ledValue); + } else if (command.substring(0, 7).equals(String("SET_LED"))) { + int set_led_value = command.substring(7).toInt(); + if ( set_led_value >= 0 && set_led_value <=100) { + ledUpdate(set_led_value); + Serial.printf("RES SET_LED 1"); + } else { + Serial.printf("RES SET_LED -1"); + } + } else { + Serial.printf("ERR Unknown command."); + } } - // Função para atualizar o valor do LED -void ledUpdate() { +void ledUpdate(int value) { // 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 + int led_value_norm = map(value, 0, 100, 0, 255); + ledValue = value; + analogWrite(ledPin, led_value_norm); } - // 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 + return map(analogRead(ldrPin), 0, ldrMax, 0, 100); } \ No newline at end of file diff --git a/teste.ino b/teste.ino new file mode 100644 index 0000000..b101620 --- /dev/null +++ b/teste.ino @@ -0,0 +1,48 @@ +// 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; +int ldrMax; +char comando; + + +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() { + comando = Serial.read(); + if( comando == 'C') + { + Serial.printf("Comando valido\n"); + } + //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() { + // 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 +} diff --git a/testeLDR.ino b/testeLDR.ino new file mode 100644 index 0000000..b759f5f --- /dev/null +++ b/testeLDR.ino @@ -0,0 +1,14 @@ +const int ldrPin = 12; +int ldrValue = 0; + +void setup() { + Serial.begin(115200); + delay(1000); +} + +void loop() { + ldrValue = analogRead(ldrPin); + Serial.print("LDR value: "); + Serial.println(ldrValue); + delay(500); +} \ No newline at end of file diff --git a/testeLed.ino b/testeLed.ino new file mode 100644 index 0000000..5ff0b7a --- /dev/null +++ b/testeLed.ino @@ -0,0 +1,22 @@ + +int ledPin = 23; +float sinVal; +int ledVal=10; + +void setup() +{ + pinMode(ledPin, OUTPUT); +} + +void loop() +{ + //normalize = map(ledVal, 0, 100, 0, 255); + for (int x=0; x<180; x++) + { + // converte graus para radianos e então obtém o valor do seno + sinVal = (sin(x*(3.1412/180))); + ledVal = int(sinVal*255); + analogWrite(ledPin, ledVal); + delay(25); + } +}