-
Posts
60 -
Cadastrado em
-
Última visita
Reputação
18-
Outro ESP8266 termostato servidor web
Igor Lima Kock respondeu ao tópico de Igor Lima Kock em Microcontroladores
Então eu tentei mas não funcionou do mesmo jeito -
Igor Lima Kock começou a seguir Chat RMI com Callback e ESP8266 termostato servidor web
-
Olá! Estou com um problema com um código para fazer um termostato junto de um servidor web num ESP8266. Segue abaixo o código em si. // Termostato com o ESP32/8266 #ifdef ESP32 #include <WiFi.h> #include <AsyncTCP.h> #else #include <ESP8266WiFi.h> #include <ESPAsyncTCP.h> #endif #include <ESPAsyncWebServer.h> #include <Wire.h> #include <OneWire.h> #include <Adafruit_Sensor.h> #include <DHT.h> // TROQUE PELAS SUAS CREDENCIAIS DE REDE const char* ssid = ""; const char* password = ""; // Temperatura limite pardão String inputMessage = "25.0"; //String getTemperature; String lastTemperature; String enableArmChecked = "checked"; String inputMessage2 = "true"; // HTML web page to handle 2 input fields (threshold_input, enable_arm_input) const char index_html[] PROGMEM = R"rawliteral( <!DOCTYPE HTML><html><head> <title>Controle do limite de temperatura</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head><body> <h2>TEMPERATURA do DHT11</h2> <h3>%TEMPERATURE% °C</h3> <h2>ESP Arm Trigger</h2> <form action="/get"> Temperature Threshold <input type="number" step="0.1" name="threshold_input" value="%THRESHOLD%" required><br> Arm Trigger <input type="checkbox" name="enable_arm_input" value="true" %ENABLE_ARM_INPUT%><br><br> <input type="submit" value="Submit"> </form> </body></html>)rawliteral"; void notFound(AsyncWebServerRequest *request) { request->send(404, "text/plain", "Not found"); } AsyncWebServer server(80); // Replaces placeholder with DS18B20 values String processor(const String& var){ //Serial.println(var); if(var == "TEMPERATURE"){ return lastTemperature; } else if(var == "THRESHOLD"){ return inputMessage; } else if(var == "ENABLE_ARM_INPUT"){ return enableArmChecked; } return String(); } // Flag variable to keep track if triggers was activated or not bool triggerActive = false; const char* PARAM_INPUT_1 = "threshold_input"; const char* PARAM_INPUT_2 = "enable_arm_input"; // Interval between sensor readings. unsigned long previousMillis = 0; const long interval = 5000; // GPIO where the output is connected to const int output = 2; // GPIO where the DHT11 is connected to const int oneWireBus = 4; // Setup a oneWire instance to communicate with any OneWire devices OneWire adafruit_Sensor(oneWireBus); // Pass our oneWire reference to DHT11 sensor //LM35 sensors(&oneWire); DHT sensors(&OneWire); //DallasTemperature sensors(&oneWire); void setup() { Serial.begin(115200); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); if (WiFi.waitForConnectResult() != WL_CONNECTED) { Serial.println("WiFi Failed!"); return; } Serial.println(); Serial.print("ESP IP Address: http://"); Serial.println(WiFi.localIP()); pinMode(output, OUTPUT); digitalWrite(output, LOW); // Start the DS18B20 sensor sensors.begin(); // Send web page to client server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ request->send_P(200, "text/html", index_html, processor); }); // Receive an HTTP GET request at <ESP_IP>/get?threshold_input=<inputMessage>&enable_arm_input=<inputMessage2> server.on("/get", HTTP_GET, [] (AsyncWebServerRequest *request) { // GET threshold_input value on <ESP_IP>/get?threshold_input=<inputMessage> if (request->hasParam(PARAM_INPUT_1)) { inputMessage = request->getParam(PARAM_INPUT_1)->value(); // GET enable_arm_input value on <ESP_IP>/get?enable_arm_input=<inputMessage2> if (request->hasParam(PARAM_INPUT_2)) { inputMessage2 = request->getParam(PARAM_INPUT_2)->value(); enableArmChecked = "checked"; } else { inputMessage2 = "false"; enableArmChecked = ""; } } Serial.println(inputMessage); Serial.println(inputMessage2); request->send(200, "text/html", "HTTP GET request sent to your ESP.<br><a href=\"/\">Return to Home Page</a>"); }); server.onNotFound(notFound); server.begin(); } void loop() { unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; //sensors.requestTemperatures(); sensors.readTemperature(); // Temperature in Celsius degrees float temperature = sensors.readTemperature(); //float temperature = lm35.getTempCByIndex(0); Serial.print(temperature); Serial.println(" *C"); // Temperature in Fahrenheit degrees /*float temperature = sensors.readTemperature(0); Serial.print(temperature); Serial.println(" *F");*/ lastTemperature = String(temperature); // Check if temperature is above threshold and if it needs to trigger output if(temperature > inputMessage.toFloat() && inputMessage2 == "true" && !triggerActive){ String message = String("Temperatura acima do limite. Temperatura atual: ") + String(temperature) + String("C"); Serial.println(message); triggerActive = true; digitalWrite(output, HIGH); } // Check if temperature is below threshold and if it needs to trigger output else if((temperature < inputMessage.toFloat()) && inputMessage2 == "true" && triggerActive) { String message = String("Temperatura abaixo do limite. Temperatura atual: ") + String(temperature) + String(" C"); Serial.println(message); triggerActive = false; digitalWrite(output, LOW); } } } Ele dá o seguinte erro error: expected primary-expression before ')' token 83 | DHT sensors(&OneWire); | ^ exit status 1 Compilation error: expected primary-expression before ')' token O que posso fazer para corrigir este erro?
-
E após isso o callback vai estar no Client?
-
Então seria assim? public String chat (String msg, String chat2) throws RemoteException{
-
e como eu poderia implementá-lo?
-
Olá desculpe a demora Ajeitei um pouco o Client, o Server e as interfaces como mostra abaixo. O Server: import java.rmi.*; import java.rmi.server.*; import java.rmi.registry.*; import java.util.Scanner; public class Server extends UnicastRemoteObject implements IIncrementa{ public String text; Scanner ler; public Server() throws RemoteException{ ler = new Scanner(System.in); } public static void main (String args[]){ try{ LocateRegistry.createRegistry(Registry.REGISTRY_PORT); Server obj_server = new Server(); Naming.rebind("rmi://127.0.0.1/Incrementa", obj_server); }catch(Exception e){ System.out.println("Erro no server"+e); } } //public void inc (IClient Obj_client, String msg) throws RemoteException{ public String chat (String msg) throws RemoteException{ System.out.println("Mensagem do Cliente: "+msg); System.out.println("Digite uma Mensagem: "); text = ler.nextLine(); return text; } } O Client: import java.rmi.*; import java.rmi.server.*; import java.util.Scanner; public class Client extends UnicastRemoteObject implements IClient{ //public class Client{ String text; public Client(String host) throws RemoteException{ try{ IIncrementa obj = (IIncrementa) Naming.lookup("rmi://"+host+"/Incrementa"); Scanner ler = new Scanner(System.in); //obj.chat2(this); while(true){ System.out.println("Digite uma mensagem: "); text = ler.nextLine(); //obj.inc(this, texto); //obj.chat2(this); } }catch(Exception e){ System.out.println("Erro no construtor"+e); } } public void callClient(String msg_cli) throws RemoteException{ System.out.println("Mensagem do Server: "+msg_cli); } public static void main (String args[]){ try{ Client obj_cli = new Client(args[0]); }catch(Exception e){ System.out.println("Erro no cliente"+e); } } } Interface 1: import java.rmi.*; public interface IIncrementa extends Remote{ public String chat (String msg, String chat2) throws RemoteException; //método que será acessado pelo cliente, somente declaração! } Interface 2: import java.rmi.*; interface IClient extends Remote{ public void callClient (String msg_cli) throws RemoteException; } Então na minha visão o Client já está com o callback incluso, gostaria de saber como eu posso colocar o callback no Server.
-
-
Olá Estou com um problema num programa que realiza um chat com um RMI com Callback Tanto o servidor e o cliente não compilam e eu já tentei de tudo para resolver isso. Segue em anexo o código do servidor, do cliente e das interfaces junto com o erro que dá na hora da compilação. Código do servidor import java.rmi.*; import java.rmi.server.*; import java.rmi.registry.*; import java.util.Scanner; public class Server extends UnicastRemoteObject implements IIncrementa{ public String text; Scanner ler; public Server() throws RemoteException{ ler = new Scanner(System.in); } public static void main (String args[]){ try{ LocateRegistry.createRegistry(Registry.REGISTRY_PORT); Server obj_server = new Server(); Naming.rebind("rmi://127.0.0.1/Incrementa", obj_server); }catch(Exception e){ System.out.println("Erro no servidor"+e); } } public void inc (IClient obj_Client, String msg) throws RemoteException{ System.out.println("Mensagem vinda do cliente: "+msg); System.out.println("Digite uma mensagem: "); text = ler.nextLine(); obj_client.callClient(text); } } Código do cliente import java.rmi.*; import java.rmi.server.*; import java.rmi.Scanner; public class Client extends UnicastRemoteObject implements IClient{ String text; public Client(String host) throws RemoteException{ try{ IIncrementa obj = (IIncrtementa) Naming.lookup("rmi://"+host+"/Incrementa"); while(true){ System.out.println("Digite uma mensagem: "); text = ler.nextLine(); obj.inc(this, text); } }catch(Exception e){ System.out.println("ERRO NO CONSTRUTOR!!!!!"+e); } public void callClient(String msg_cli) throws RemoteException{ System.out.println("Mensagem do server: "+msg_cli); } public static void main (String args[]){ try{ Client obj_cli = new Client(args[0]); }catch(Exception e){ System.out.println("Erro no cliente"+e); } } } } Código da interface 1 import java.rmi.*; public interface IIncrementa extends Remote{ public String chat (String msg) throws RemoteException; //método que será acessado pelo cliente, somente declaração! } Código da interface 2 import java.rmi.*; interface IClient extends Remote{ public void callClient (String msg_cli) throws RemoteException; } Os erros que dão na hora de compilar: Do Cliente: Do Servidor:
-
Olá! O código é para fazer um caça palavras em c que leia 20 palavras, cada palavra deve ter entre 5 e 10 letras. Após isso, as palavra devem ser passadas para uma função externa que deve sortear a posição e Direção da palavra dentro de uma matriz de 16x16. Alem de sortear a Direção, o programa deve impedir que as palavras saiam da matriz ou sejam colocadas sobre outras já existentes. Segue o código abaixo. #include<stdio.h> #include<locale.h> #include<string.h> #include<stdlib.h> /*Trabalho de programaçao. */ char boas_vindas(){//Dá boas vindas. printf("Olá, isso é um CAÇA-PALAVRAS em c++.\nVocê deverá informar 20 palavras para compor o quadro\n\nElas deverão ter de 5 a 10 letras.\n\n\n");} struct palavras{ char pala[10]; double situacao;}; char esconder(char *q){ char letras[26] = {"abcdefghijklmnopqrstuvxwyz"}; int i, j, n, a, t; i=0; while(i<256){ n=rand()%26; if(*q!='\0' && *q=='$'){*q=letras[n];} i++; q++;}} char colocar_palavra(int l, char palavra[10], char p[16][16], char *n){ int posj, posi, pi, pj, dir, i, j, a, b; int x, y, o, t, s; a=0; while(a==0){ posi=rand()%16; posj=rand()%16; b=0; o=0; while(b==0 || o<36){ dir=rand()%6; i=posi; j=posj; t=0; //=====Verificaçao 1====== {Se esta dentro dos limites da matriz} if(dir!=0){ if(dir==1){/*Direita*/ j=j+l-1;} else { if(dir==2){/*Esquerda*/ j=j-l+1;} else { if(dir==3){/*Cima*/ i=i-l+1;} else { if(dir==4){/*Baixo*/ i=i+l-1;} else { if(dir==5){/*Diagonal Cima*/ i=i-l+1; j=j-l+1;} else { if(dir==6){/*Diagonal Baixo*/ i=i+l-1; j=j+l-1;}}}}}} //======================== //======Verificaçao 2====== if(j>=0 && j<=15 && i>=0 && i<=15){ if(dir==1){for(x=0, pi=posi, pj=posj, t=0; x!=l; x++){if(p[pi][pj] == palavra[x]){t++;} pj++;}} else { if(dir==2){for(x=0, pi=posi, pj=posj, t=0; x!=l; x++){if(p[pi][pj] == palavra[x]){t++;} posj--;}} else { if(dir==3){for(x=0, pi=posi, pj=posj, t=0; x!=l; x++){if(p[pi][pj] == palavra[x]){t++;} posi--;}} else { if(dir==4){for(x=0, pi=posi, pj=posj, t=0; x!=l; x++){if(p[pi][pj] == palavra[x]){t++;} posi++;}} else { if(dir==5){for(x=0, pi=posi, pj=posj, t=0; x!=l; x++){if(p[pi][pj] == palavra[x]){t++;} posi--; posj--;}} else { if(dir==6){for(x=0, pi=posi, pj=posj, t=0; x!=l; x++){if(p[pi][pj] == palavra[x]){t++;} posi++; posj++;}}}}}}} if(t<=1){b=1;} else {b=0;} } else {b=0;}} else {b=0;} o++;}if(b==1){a=1;} else {a=0;}} //======Coloca a palavra======== if(dir==1){for(x=0; x!=l; x++){p[posi][posj]=palavra[x]; posj++;}} else { if(dir==2){for(x=0; x!=l; x++){p[posi][posj]=palavra[x]; posj--;}} else { if(dir==3){for(x=0; x!=l; x++){p[posi][posj]=palavra[x]; posi--;}} else { if(dir==4){for(x=0; x!=l; x++){p[posi][posj]=palavra[x]; posi++;}} else { if(dir==5){for(x=0; x!=l; x++){p[posi][posj]=palavra[x]; posi--; posj--;}} else { if(dir==6){for(x=0; x!=l; x++){p[posi][posj]=palavra[x]; posi++; posj++;}}}}}}} //printf("%d\n", dir); //============================== printf("\n\n"); for(i=0; i<16; i++){for(j=0; j<16; j++){printf("%c ", p[i][j]);} printf("\n");} //=====Retorno================== for(i=0; i<16; i++){for(j=0; j<16; j++){*n=p[i][j]; n++;}}} main(){ char p[16][16], palavra[10], *t, dir[15]; int i, j, l, q, c; struct palavras n[20]; srand((unsigned)time(NULL)); // -----------------Limpador ---------------- t=&p; i=(int) t +257; for( ; t<i; t++){*t='$';} // ------------------------------------------ boas_vindas(); //--------------Recebe a palavra------------- for(q=0; q<20; q++){printf("\nInforme a palavra %d:", q+1); l=0; while(l<5 || l>10){gets(palavra); for(l=0; palavra[l]!='\0'; l++); if(l<5 || l>10){printf("\nOpps, tente outra:");}} colocar_palavra(l, palavra, p, p); //=====Armazena palavra======= strcpy(n[q].pala, palavra); n[q].situacao=0; l=0;} //=======Esconde========== if(p[0][0]=='\n'){p[0][0]='$';} esconder(p); printf("\n\n\n"); for(i=0; i<16; i++){ for(j=0; j<16; j++){printf("%c ", p[i][j]);} printf("\n");} printf("\n\n Palavras a serem procuradas:\n"); for(q=0; q<20; q++){printf("%s ", n[q].pala); if(q%4==0 && q!=0){printf("\n");}} printf("\n\nVamos procurar. voce deve informar a palavra, direcao e posicao:\n"); while(q>=0){ printf("Informe a palavra:"); gets(palavra); printf("Informe a direcao (cima, baixo, esquerda, direita, diagonal cima, diagonal baixo):"); gets(dir); printf("Informe posicao (L) (C) [Ex: 12 0]:"); scanf("%d %d", &l, &c); if(i==0){printf("Nao encontrado.");} else {q--;} } } O problema é que o código continua tendo colisões mesmo ele verificando que as colisões não acontecem (A verificação está na parte do (======Verificação 2=======) ). O que pode estar causando isso? Se puderem me ajudar eu ficaria agradecido.
-
Outro WNeander lados do triangulo
Igor Lima Kock respondeu ao tópico de Igor Lima Kock em Programação - outros
@devair1010 Já consegui obrigado -
Outro WNeander lados do triangulo
Igor Lima Kock respondeu ao tópico de Igor Lima Kock em Programação - outros
@devair1010 O programa que você usa é totalmente diferente do meu -
Outro WNeander lados do triangulo
Igor Lima Kock respondeu ao tópico de Igor Lima Kock em Programação - outros
@devair1010 mais ou menos -
Outro WNeander lados do triangulo
Igor Lima Kock respondeu ao tópico de Igor Lima Kock em Programação - outros
Já fiz alguns códigos nele sim mas era coisa mais básica tipo soma, subtração, multiplicação e essas coisas o que o meu professor deu -
Outro WNeander lados do triangulo
Igor Lima Kock respondeu ao tópico de Igor Lima Kock em Programação - outros
Eu sei como o neander funciona meu amigo, eu não sei como começar o exercício em si porque o básico eu sei. -
Olá! Não estou conseguindo fazer esta questão no WNeander aqui "Crie um programa que verifique os lado de um triângulo e diga, se é um triângulo é isósceles (1), equilátero(2) ou escaleno (3). Para tal o programa deve receber os valores de cada um dos lados do triângulo, e em uma posição de memória deve ser exibido o resulta, ou seja, o número que representa um tipo de triângulo." Se alguém puder me ajudar eu agradeço.
Sobre o Clube do Hardware
No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais
Direitos autorais
Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais