Hy guys I´m trying to send a message from my phone in a server ESP32 but any app tcp connection that I try returns me disconnected. Im doing somehing wrong? my code is missing something... I don´t know
#include <Arduino.h>
#include <WiFi.h>
#include "NetManager.hpp"
constexpr char SSID[] = "ESP32Server";
constexpr char PASSWORD[] = "12345678";
constexpr int SERVER_PORT = 80;
NetManager netManager(SERVER_PORT, SSID, PASSWORD);
int temperature = 24;
void handleCommandReceive(int command)
{
temperature = command;
}
int handleCommandSend()
{
return temperature;
}
void setup()
{
Serial.begin(115200);
netManager.setup(handleCommandReceive, handleCommandSend);
}
void loop()
{
netManager.loop();
delay(10);
}
Complete code
https://github.com/ProjetosESP32/air-esp
I tried in Flutter too with a socket package but i got same error
Related
I have been trying to connect my ESP32 with HiveMQ MQTT broker url. It connects when I use free public MQTT broker like broker.hivemq.com, but when I use my url which I got after registering in HiveMQ, it doesn't connect. It returns error with code 2.
I have used this MQTT broker url with windows MQTT client app and it works fine but it doesn't work with ESP32.
#include <WiFi.h>
#include <PubSubClient.h>
// WiFi
const char *ssid = "********"; // Enter your WiFi name
const char *password = "********"; // Enter WiFi password
// MQTT Broker
const char *mqtt_broker = "591c2cacc87d4e248d106212ae6e0d4f.s2.eu.hivemq.cloud";
const char *topic = "esp32/test";
const char *mqtt_username = "*******";
const char *mqtt_password = "*******";
const int mqtt_port = 8883;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
// Set software serial baud to 115200;
Serial.begin(115200);
// connecting to a WiFi network
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
//connecting to a mqtt broker
client.setServer(mqtt_broker, mqtt_port);
client.setCallback(callback);
while (!client.connected()) {
String client_id = "esp32-client-";
client_id += String(WiFi.macAddress());
Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str());
if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
Serial.println("Public emqx mqtt broker connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
// publish and subscribe
client.publish(topic, "Hi EMQ X I'm ESP32 ^^");
client.subscribe(topic);
}
void callback(char *topic, byte *payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char) payload[i]);
}
Serial.println();
Serial.println("-----------------------");
}
void loop() {
client.loop();
}
In the comments, #hcheung said:
When you use MQTT over TLS (port 8883), you need to use WiFiClientSecure.h and add the root CA of broker.hivemq.com to your sketch. Refer to WiFiClientSecure on how to do it.
You can get the root CA of your HiveMQ broker with the following OpenSSL method:
openssl s_client -connect hivemq-broker-host:8883 -showcerts
Change hivemq-broker-host with your MQTT host.
Using a combination of Farhan's example and a few other examples I found elsewhere, I was able to get this to work.
First, open a terminal run the command from Johnny Boy's answer (This assumes you have openssl installed. If not, install it.
openssl s_client -connect YOUR_URL.hivemq.cloud:8883 -showcerts
You'll get three certificates. They look like this
-----BEGIN CERTIFICATE----- MIIFYDCCBEigAwIBAgIQQAF3ITfU6UK47naqPGQKtzANBgkqhkiG9w0BAQsFADA/
MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT
DkRTVCBSb290IENBIFgzMB4XDTIxMDEyMDE5MTQwM1oXDTI0MDkzMDE4MTQwM1ow
...Lots more characters that I'll omit for brevity...
-----END CERTIFICATE-----
The third certificate is the one you want. Copy this certificate out of your terminal (including the BEGIN and END CERTIFICATE parts). Paste the cert into your ESP32 code as a const char variable, such as:
const char *ROOT_CERT = "-----BEGIN CERTIFICATE-----\n"
"MIIFYDCCBEigAwIBAgIQQAF3ITfU6UK47naqPGQKtzANBgkqhkiG9w0BAQsFADA/\n"
"MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\n"
... etc..
Using the WiFiClientSecure library mentioned in the comments, use the setCACert function to utilize your certificate. The rest of the code looks pretty close to what Farhan had. In my example, a few of the variables, including the ROOT_CERT variable from above, were defined in another file (WifiCredentials.h):
#include <PubSubClient.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiServer.h>
#include <WiFiUdp.h>
#include "WifiCredentials.h"
#include <WiFiClientSecure.h>
*********/
Helpful References:
* https://randomnerdtutorials.com/esp32-web-server-arduino-ide/
*
*********/
WiFiClientSecure wifiClient;
PubSubClient mqttClient(wifiClient);
char *mqttServer = "YOUR_URL.hivemq.cloud";
int mqttPort = 8883;
const char *mqtt_password = "password_I_setup_at_hivemq";
const char *mqtt_username = "username_I-setup_at_hivemq";
void setup() {
Serial.begin(9600);
// Connect to Wi-Fi network
Serial.print("Connecting to ");
Serial.println(WifiSSID);
WiFi.begin(WifiSSID, WifiPassword);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("...Still Connecting");
}
Serial.println("");
Serial.println("WiFi connected.");
wifiClient.setCACert(ROOT_CERT);
}
void loop(){
if (!mqttClient.connected()) {
mqttClient.setServer(mqttServer, mqttPort);
// set the callback function
mqttClient.setCallback(callback);
Serial.println("Connecting to MQTT Broker...");
while (!mqttClient.connected()) {
Serial.println("Reconnecting to MQTT Broker..");
String clientId = "ESP32Client-";
clientId += String(random(0xffff), HEX);
if (mqttClient.connect(clientId.c_str(), mqtt_username, mqtt_password)) {
Serial.println("Connected to MQTT BRoker!.");
// subscribe to topic
mqttClient.subscribe("/transactions/device1");
mqttClient.publish("/transactions/device1", "testing hello");
} else {
Serial.print("failed with state ");
Serial.print(mqttClient.state());
delay(2000);
}
}
}
mqttClient.loop();
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Callback - ");
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
}
Connect a tool like MQTT Dash to your HiveMQ instance, open a serial monitor, and test your code.
I am connecting a sensor to android device through arduino. I need to encrypt my sensor data and then send it to android device. But when I include aes128_enc_single(key, temp), It gives an error and said "aes128_enc_single' was not declared in this scope "
What should I do for this?
I have included AESLib.h library
My sample code is
#include <SoftwareSerial.h>
#include <Adafruit_Sensor.h>
#include <AESLib.h>
uint8_t key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};
SoftwareSerial blue(2,3);
int i = 0;
float temp = 0;
void setup() {
Serial.begin(9600);
blue.begin(9600);
}
void loop() {
i = analogRead(A0);
temp = (i/1024.0)*500;
Serial.println(temp);
aes128_enc_single(key, temp);
Serial.print("encrypted:");
Serial.println(temp);
blue.print("Encrypted Temperature: ");
blue.println(temp);
delay(1000);
}
I have a sketch working with an Arduino Uno and an Ethernet Shield - and it's working fine. Now I've gotten my hands on some Arduino Uno WiFi, and I want to port the sketch from ethernet to wifi - but I've run into a wall now. Most of the guide/FAQ/help I can find is for a WiFi Shield, and not a WiFi Arduino, so I'm stuck here.
Below is my (original Ethernet) code. I can post my somewhat modified Wifi code, but I can't even compile it without errors.
// Hartmann fugtighedsmåler v 0.1
// Lavet af Jan Andreasen
// Skriver til DB på FDKTO517
#include <Ethernet.h>
#include <SPI.h>
#include <DHT.h>
#define DHTPIN 2 // Siger sig selv
#define DHTTYPE DHT11 // Typen af sensor.
float h = 0;
float t = 0;
byte mac[] = {0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02}; // Macadresse på kortet
IPAddress server(10,16,9,229); // Server adressen på SQL'en
EthernetClient client;
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println("Starting...");
Ethernet.begin(mac);
dht.begin();
}
void loop() {
readTempHum();
delay(300000); // Loop timer i millis - 5 minutter
}
void get_request(float t, float h) {
Serial.println("Connecting to Client...");
if (client.connect(server, 10080)) {
Serial.println("--> connection ok\n");
client.print("GET /test.php?");
// Placering af PHP script til upload til DB
client.print("t="); // Temp
client.print(t);
client.print("&h="); // Fugtighed
client.print(h);
client.println(" HTTP/1.1");
client.print( "Host: " );
client.println(server);
client.println("Connection: close");
client.println();
client.println();
client.stop();
Serial.println("--> finished transmission\n");
} else {
Serial.println("--> connection failed\n");
}
}
void readTempHum() {
h = dht.readHumidity();
t = dht.readTemperature();
{
Serial.print("Humidity: ");
Serial.print(h);
Serial.print("%\t");
Serial.print("Temperature:");
Serial.print(t);
Serial.println("*C");
get_request(t,h);
}
}
I've also posted this on the Arduino Forum. I'm sorry if you see my double-post, and I'll post the solution to my problem here as well.
New sketch:
#include <Wire.h>
#include <UnoWiFiDevEd.h>
#include <DHT.h>
#define DHTPIN 4
#define DHTTYPE DHT11
float h = 0;
float t = 0;
DHT dht(DHTPIN, DHTTYPE);
void setup() {
const char* connector = "rest";
const char* server = "10.16.9.229";
const char* method = "GET";
const char* resource = "/test.php?t=";
Serial.begin(9600);
Ciao.begin();
dht.begin();
pinMode(2, INPUT);
delay(10000);
}
void loop() {
readTempHum();
// doRequest(connector, server, resource, method);
delay(300000);
}
void doRequest(const char* conn, const char* server, const char* command, const char* method, float t, float h){
CiaoData data = Ciao.write(conn, server, command, method);
}
void readTempHum() {
h = dht.readHumidity();
t = dht.readTemperature();
const char* connector = "rest";
const char* server = "10.16.9.229";
const char* method = "GET";
const char* resource = "/test.php?t=";
{
doRequest(connector, server, resource, method,t,h);
}
}
Now, I've ran into a new problem. The value from the sensor (t and h) are supposed to be output in the HTTP/GET command like this:
test.php?t=1&h=2
But I can't seem to make that work. If I try to define the resource as this
const char* resource = "/test.php?t="+t+"&h="+h;
I get an error (obviously), but if I try to declare it as a string, I the same error again.
Error:
HumidSQL3_Wifi_master:24: error: invalid operands of types 'const char [13]' and 'float' to binary 'operator+'
const char* resource = "/test.php?t="+t+"&h="+h;
Now, I hope that some of you could help me out a bit here :/
If it is the Arduino.org Arduino UNO WiFi Developer Edition, then use WiFi Link with UNO WiFi Serial1 library
Okay - so I made it work. I had to start from scratch, and with the help from Juraj (I'll accept your answer as well) it works now.
Below are the final sketch ("final", as the DHT11 sensor only were for testing purpose, as a proof-of-concept)
// Hartmann fugtighedsmåler v 0.2.2
// Lavet af Jan Andreasen
// Skriver til DB på FDKTO517
// WiFi udgave, testversion
#include <Wire.h>
#include <UnoWiFiDevEd.h>
#include <DHT.h>
#define DHTPIN 4
#define DHTTYPE DHT11
#define CONNECTOR "rest"
#define SERVER_ADDR "10.16.9.229"
float h = 0;
float t = 0;
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Ciao.begin();
dht.begin();
pinMode(2, INPUT); // I'm not sure if this is required, just saw it now
delay(10000); // A 10 second delay from start to initialization
}
void loop() {
readTempHum();
delay(300000); // A 5 minute delay between measurements
}
void readTempHum() {
h = dht.readHumidity(); // Reads the humidity from sensor
t = dht.readTemperature(); // Reads the temperature from sensor
String uri = "/test.php?t="; // URL to the PHP-file
uri += t; // Insert the T-value
uri +="&h=";
uri += h; // Insert the H-value
CiaoData data = Ciao.write(CONNECTOR, SERVER_ADDR, uri); // Make a basic HTTP request to the specified server using REST and the URL specified above
}
Maybe not the prettiest code you've seen, however, it works now.
My goal is to essentially spoof RSSI (Received Signal Strength Indicator) using a system of counting received packets. The idea is to have something where:
A specific number of packets is sent in a specific time from the transmitter.
Then are received at another unit and the number of packets received is counted.
The number in the counter of the receiver indicates the number of packets received at that time specific in the transmitter.
The fewer packages (counter value) that are received, the farther the sender will be.
I'm having a little trouble implementing the logic in my code however so I'd really appreciate the help. I am using Arduino Pro Mini 5V with NRF24L01+ radios and the RF24 Network library. My code is as follows:
Transmitter:
#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>
#include <Wire.h>
RF24 radio(8,9);
RF24Network network(radio);
const uint16_t home_node = 00;
const uint16_t distant_node = 01;
struct payload_t { // Structure of our payload
byte ID;
};
void setup(void) {
Serial.begin(115200);
SPI.begin();
radio.begin();
network.begin(/*channel*/ 92, /*node address*/ distant_node);
}
void loop(void) {
byte ID = 1;
for (int i = 0; i < 50; i++)
{
payload_t payload = {ID};
RF24NetworkHeader header(/*to node*/ home_node);
bool ok = network.write(header,&payload,sizeof(payload));
if (ok)
Serial.println("ok.");
else
Serial.println("failed.");
delay (300);
}
delay(15000);
}
Receiver:
#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>
#include <Wire.h>
RF24 radio(8,9);
RF24Network network(radio);
const uint16_t home_node = 00;
const uint16_t distant_node = 01;
struct payload_t {
byte ID;
};
//const unsigned long interval = 3000;
//unsigned long last_sent;
int count = 0;
void setup(void)
{
Serial.begin(115200);
SPI.begin();
radio.begin();
network.begin(/*channel*/ 92, /*node address*/ home_node);
}
void loop(void)
{
RF24NetworkHeader header;
payload_t payload;
network.update();
while ( network.available() ) { // Is there anything ready for us?
bool ok = network.read(header, &payload, sizeof(payload));
if (ok) // Non-blocking
{
count++;
Serial.println ("count=");
Serial.println (count);
}
else
Serial.println ("Failed");
}
}
I have followed the steps outlined in the following link to install and run the Mosquitto broker on my laptop.
https://sivatechworld.wordpress.com/2015/06/11/step-by-step-installing-and-configuring-mosquitto-with-windows-7/
I have tested the publishing and subscription events using command line i.e, the mosquitto_pub and mosquitto_sub commands and they worked fine!
I want to publish to this broker running on my laptop (listening to port 1883 - confirmed using the netstat-an command) using an Arduino which is using the functions from "PubSubClient" library.
For the server's IP address in the Arduino Publish sketch, I have given the IP address of my laptop itself which it gets when it connects to my home network. Following is the publisher code:
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
#define CLIENTID "Arsen"
const char topic[] = "tem";
#define POLLINTERVAL 120000
void callback(char* topic, byte* payload, unsigned int length){
//Do nothing as we are publishing ONLY.
}
byte mac [] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED} ;
IPAddress server(192, 168, 0, 10);
EthernetClient ethClient;
PubSubClient arduinoClient(server,1883, callback, ethClient) ;
unsigned long boardTime = 0 ;
float sensedTemperature = 0;
char charTemp [6];
int connRC = 0;
void setup(void) {
Serial.begin(9600);
//Connect to the MQTT server - test.mosquitto.org
beginConnection() ;
}
//Initialise MQTT connection
void beginConnection() {
Serial.begin(9600);
Ethernet.begin(mac) ; //using the address assigned through DHCP
do{
int connRC = arduinoClient.connect(CLIENTID);
}while(connRC==1);
Serial.println("We are connected finally");
delay(5000);
Serial.println(arduinoClient.state());
}
void loop(void) {
boardTime = millis();
if ((boardTime % POLLINTERVAL) == 0) {
getTemp();
dtostrf(sensedTemperature,5,2,charTemp);
boolean rec = arduinoClient.publish(topic, charTemp);
Serial.println(rec);
Serial.println("Successfully published");
}
arduinoClient.loop();
}
void getTemp() {
// Send the command to get temperatures
delay(100);
sensedTemperature = analogRead(2); //temperature sensor at analog pin 2 on Arduino.
Serial.println(sensedTemperature);
delay(150);
}
The subscriber code is:
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <EthernetServer.h>
#include <EthernetClient.h>
#include <Dns.h>
#include <Dhcp.h>
#include <SPI.h>
#include <PubSubClient.h>
#define PIN 13
//MQTT Definition
#define CLIENTID "Aract"
#define TOPICNAME "tem"
byte mac [] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED} ;
IPAddress server(192,168,0,5); // Mosquitto Server
int connRC = 0;
//Handle message from mosquitto and set LEDs
void callback(char* topic, byte* payload, unsigned int length) {
int i=0; char buffer [length];
for(i=0;i<length;i++) {
buffer [i] = char((payload[i]));
}
String payLoadData = buffer;
Serial.println(payLoadData);
setled(payLoadData);
}
//Our MQTT client
EthernetClient ethclient;
PubSubClient arduinoClient(server, 1883, callback, ethclient) ;
void setup() {
//Connect to the MQTT server - test.mosquitto.org
beginConnection() ;
}
//Initialise MQTT connection
void beginConnection() {
Serial.begin(9600);
Ethernet.begin(mac) ;
do{
connRC = arduinoClient.connect(CLIENTID) ;
delay(2000);
}while(connRC==1);
delay(3000);
Serial.println(arduinoClient.state());
if (connRC==1) {
boolean rec = arduinoClient.subscribe(TOPICNAME) ;
Serial.println(rec);
Serial.println("Successfully Subscribed");
} else {
Serial.println("connRC") ;
}
}
void loop()
{
arduinoClient.loop() ;
}
void setled(String s)
{
int temperature;
temperature = s.toInt();
Serial.println(temperature);
if (temperature >= 200){
digitalWrite(PIN, HIGH);
}
else{
digitalWrite(PIN, LOW);
}
}
The Ethernet shield is working well as it successfully executed the example programs. The state function returns "zero" which implies that the board is connecting to the network. However, the publish command returns a boolean value "rec" which is giving false. I want to know as to why this process is being unsuccessful all the time?
The verbose option (-v) along with Mosquitto on command line throws up an unknown error instead of showing the logged details. How to overcome this problem or what exactly is wrong in my technique?
I had faced the same problem and I got the solution as this...
Just go to the services running in your PC and stop the mosquitto-broker, now open the cmd and change the directory to the place where mosuitto files were located (in my case it is "cd C:\Program Files (x86)\mosquitto") and then enter this command mosquitto -v, now just left that window like that (If u closed then it won't work)...
It really worked and the reason why its not working in before case is, when we started moquitto-broker service then its not opening ports for IPv4 and here is the reference "Mosquitto Error"