Arduino UNO WiFi Rev 2 not posting to SSL connections - ssl

I've been having an issue trying to get my UNO WiFi Rev 2 to make a POST request to my https azure server. I've been able to successfully POST to this server using a MKR1000 using the WiFi101 library, so it's weird that I can't get the UNO to POST using the WiFiNINA library. I've tried two approaches to this POST request, if anybody could offer a solution to either of them, I would appreciate it.
My first attempt was based off the WiFININA libary's example for HTTPS POST:
This example creates a client object that connects and transfers
data using always SSL.
It is compatible with the methods normally related to plain
connections, like client.connect(host, port).
Written by Arturo Guadalupi
last revision November 2015
*/
#include <SPI.h>
#include <WiFiNINA.h>
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = "secret"; // your network SSID (name)
char pass[] = "secret"; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key index number (needed only for WEP)
int status = WL_IDLE_STATUS;
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS)
char server[] = "secret"; // name address for Google (using DNS)
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
int HTTP_PORT = 443;
String HTTP_METHOD = "POST";
char HOST_NAME[] = "secret";
//IPAddress server(secret);
String PATH_NAME = "/wtid/logCovid";
WiFiSSLClient client;
String queryString = "uuid=5555&manufacturerID=6666";
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the WiFi module:
if (WiFi.status() == WL_NO_MODULE) {
Serial.println("Communication with WiFi module failed!");
// don't continue
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
Serial.println("Please upgrade the firmware");
}
// attempt to connect to WiFi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println("Connected to WiFi");
printWiFiStatus();
Serial.println("\nStarting connection to server...");
// if you get a connection, report back via serial:
if (client.connect(server, HTTP_PORT)) {
Serial.println("connected to server");
// Make a HTTP request:
// MUST HAVE THESE HEADERS AND IN THIS ORDER!!!
client.println(HTTP_METHOD + " " + PATH_NAME + " HTTP/1.1");
client.println("Host: " + String(HOST_NAME));
client.println("User-Agent: Arduino/1.0");
client.println("Connection: close");
client.println("Content-Type: application/x-www-form-urlencoded");
client.print("Content-Length: ");
client.println(queryString.length());
client.println();
// Body AKA the data we are sending to the server
client.print(queryString);
}
}
void loop() {
// if there are incoming bytes available
// from the server, read them and print them:
while (client.available()) {
char c = client.read();
Serial.write(c);
}
// if the server's disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting from server.");
client.stop();
// do nothing forevermore:
while (true);
}
}
void printWiFiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your board's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
Here is the Serial monitor response whenever I upload that script:
Starting connection to server...
disconnecting from server.
My second approach was using the ArduinoHttpClient with a WiFiSSLClient, but again no luck:
#include <ArduinoHttpClient.h>
#include <WiFiNINA.h>
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
/////// WiFi Settings ///////
char ssid[] = "secret"; // your network SSID (name)
char pass[] = "secret"; // your network password (use for WPA, or use as key for WEP)
char serverAddress[] = "secret"; // server address
int port = 443;
WiFiSSLClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS;
void setup() {
Serial.begin(9600);
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid); // print the network name (SSID);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
}
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
}
void loop() {
Serial.println("making POST request");
String contentType = "application/x-www-form-urlencoded";
String postData = "uuid=4444&manufacturerID=5555";
client.post("/wtid/logCovid", contentType, postData);
// read the status code and body of the response
int statusCode = client.responseStatusCode();
String response = client.responseBody();
Serial.print("Status code: ");
Serial.println(statusCode);
Serial.print("Response: ");
Serial.println(response);
Serial.println("Wait five seconds");
delay(5000);
}
Here is the Serial monitor response whenever I upload that script:
making POST request
Status code: -2
Response:
Wait five seconds
I've updated the WiFiNINA firmware and uploaded the SSL certificates via the arduino IDE to the board as well, and I am able to make SSL GET requests to sites like google.com without issue. I do get Serial responses ensuring that I connected to the wifi, just didn't want to put that part of the Serial monitor response.
Thank you to anyone who can help!
:)

Related

Failed to connect to Hivemq and arduino state=2

I am trying to connect my ESP8266 board on my server in HiveMQ. Knowing that the in update would be a TLS-based connection, I had to adapt my code. However, so far I have not been able to stabilize the connection. Although I can upload the code to esp, it sends me the message: Attempting MQTT connection...failed, rc=-2 try again in 5 seconds.
Note: The hivemq Guide is wrong, many problems) I have installed OPENssl to get the certificates, but none of the three appeared to work. I'm waiting for help, please.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <WiFiClientSecure.h>
//---- WiFi settings
const char* ssid ="myssid";
const char* password = "mypass";
//---- MQTT Broker settings
const char* mqtt_server = "06f141f33c074deab7c362e9cf1f3eee.s1.eu.hivemq.cloud";
// This is my broker
const char* mqtt_username = "myuser";
const char* mqtt_password = "mypass";
const int mqtt_port =8883;
WiFiClientSecure espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
const char* sensor1_topic= "temperatura";
const char* sensor2_topic="umidade";
const char *x509CA PROGMEM = R"EOF("
-----BEGIN CERTIFICATE-----
MIIFFjCCAv6gAwIBAgIRAJErCEr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k5HPqP3hUSFvNVneLKYY611TR6W
PTNlclQtgaDqw+34IL9fzLdwALduO/ZelN7kIJ+m74uyA+eitRY8kc607TkC53wl
ikfmZW4/RvTZ8M6UK+5UzhK8jCdLuMGYL6KvzXGRSgi3yLgjewQtCPkIVz6D2QQz
CkcheAmCJ8MqyJu5zlzyZMjAvnnAT45tRAxekrsu94sQ4egdRCnbWSDtY7kh+BIm
lJNXoB1lBMEKIq4QDUOXoRgffuDghje1WrG9ML+Hbisq/yFOGwXD9RiX8F6sw6W4
avAuvDszue5L3sz85K+EC4Y/wFVDNvZo4TYXao6Z0f+lQKc0t8DQYzk1OXVu8rp2
yJMC6alLbBfODALZvYH7n7do1AZls4I9d1P4jnkDrQoxB3UqQ9hVl3LEKQ73xF1O
yK5GhDDX8oVfGKF5u+decIsH4YaTw7mP3GFxJSqv3+0lUFJoi5Lc5da149p90Ids
hCExroL1+7mryIkXPeFM5TgO9r0rvZaBFOvV2z0gp35Z0+L4WPlbuEjN/lxPFin+
HlUjr8gRsI3qfJOQFy/9rKIJR0Y/8Omwt/8oTWgy1mdeHmmjk7j1nYsvC9JSQ6Zv
MldlTTKB3zhThV1+XWYp6rjd5JW1zbVWEkLNxE7GJThEUG3szgBVGP7pSWTUTsqX
nLRbwHOoq7hHwg==
-----END CERTIFICATE-----
")EOF";
void setup() {
Serial.begin(9600);
Serial.print("\nConnecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("\nWiFi connected\nIP address: ");
Serial.println(WiFi.localIP());
while (!Serial) delay(1);
espClient.setCACert((const uint8_t*)x509CA, sizeof(x509CA) - 1);
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) reconnect();
client.loop();
publishMessage(sensor1_topic,String("XXXX"),true);
publishMessage(sensor2_topic,String("XXXX"),true);
}
//=======================================================================Function=================================================================================
void reconnect() {
// Loop until we’re reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection…");
String clientId = "ESP8266Client"; // Create a random client ID
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str(), mqtt_username, mqtt_password)) {
Serial.println("connected");
client.subscribe(sensor1_topic); // subscribe the topics here
//client.subscribe(command2_topic); // subscribe the topics here
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying
delay(5000);
}
}
}
//=======================================
// This void is called every time we have a message from the broker
void callback(char* topic, byte* payload, unsigned int length) {
String incomingMessage = "HELLO";
for (int i = 0; i < length; i++) incomingMessage+=(char)payload[i];
Serial.println("Message arrived");
// check for other commands
/* else if( strcmp(topic,command2_topic) == 0){
if (incomingMessage.equals(“1”)) { } // do something else
}
*/
}
//======================================= publising as string
void publishMessage(const char* topic, String payload , boolean retained){
if (client.publish(topic, payload.c_str(), true))
Serial.println("Published");
}
After talking with another colleague, he came to a conclusion that perhaps an ESP8266 does not support TLS connections due to its low memory capacity, and that a better resolution is to bypass an encryption by adding the following code:
replace: espClient.setCACert((const uint8_t*)x509CA, sizeof(x509CA) - 1);
for: espClient.setInsecure();
I also had plans to connect an ESP8266 board to HiveMQ when I saw this question. Although the original poster has decided not to check the server certificate against a CA certificate, I did manage to get this part working so thought I would still post my answer as it may be helpful.
When using WifiClientSecure there are several options that can be used to check the remote server's identity. These options are controlled by separate method calls (see also BearSSL Wifi Classes):
setInsecure() - this bypasses the checking of the server certificate completely, so although the TLS connection is established we cannot guarantee that the server is actually HiveMQ.
setKnownKey() - we provide the complete public key we expect to receive from HiveMQ (can be found using openssl s_client). The connect will fail if HiveMQ update their certificate.
setFingerprint() - similar to setKnownKey() but here we just check the SHA1 fingerprint of the server's public key. Again, the connect will fail if HiveMQ update their certificate.
setTrustAnchors() - this will check that the server certificate has been signed by a certificate in the provided CA list and check the identity of the server. This has the advantage of working even if HiveMQ update their server certificate - as long as their CA remains the same. CA certificates typically have a longer lifespan than server certificates. However, in order to validate the server certificate, the WifiClientSecure object needs to know the current time, which we can set using the setX509Time() method. This means we need to fetch the current time from an NTP server. (Note setCACert() is deprecated in the latest code base).
The following code shows a connection to HiveMQ using setTrustAnchors() with a single CA certificate. (Again this certficate can be found using openssl s_client to connect to HiveMQ and look at which CA signed the certificate).
#include <NTPClient.h>
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <WiFiUdp.h>
#include <PubSubClient.h>
const String MQTT_HOST("0123456789abcdef0123456789abcdef.s1.eu.hivemq.cloud");
const int MQTT_PORT = 8883 ;
const String MQTT_CLIENT_ID("test_hive_client_1");
const String MQTT_USER("mqttuser");
const String MQTT_PWD("secretpassword");
String wifiSid = "MY_WIFI_SID";
String wifiPwd = "anothersecretpassword";
// The CA certificate used to sign the HiveMQ server certificate
static const char caCert[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIFFjCCAv6gAwIBAgIRAJErCErPDBinU/bWLiWnX1owDQYJKoZIhvcNAQELBQAw
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMjAwOTA0MDAwMDAw
WhcNMjUwOTE1MTYwMDAwWjAyMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNTGV0J3Mg
RW5jcnlwdDELMAkGA1UEAxMCUjMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
AoIBAQC7AhUozPaglNMPEuyNVZLD+ILxmaZ6QoinXSaqtSu5xUyxr45r+XXIo9cP
R5QUVTVXjJ6oojkZ9YI8QqlObvU7wy7bjcCwXPNZOOftz2nwWgsbvsCUJCWH+jdx
sxPnHKzhm+/b5DtFUkWWqcFTzjTIUu61ru2P3mBw4qVUq7ZtDpelQDRrK9O8Zutm
NHz6a4uPVymZ+DAXXbpyb/uBxa3Shlg9F8fnCbvxK/e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gRsI3qfJOQFy/9rKIJR0Y/8Omwt/8oTWgy1mdeHmmjk7j1nYsvC9JSQ6Zv
MldlTTKB3zhThV1+XWYp6rjd5JW1zbVWEkLNxE7GJThEUG3szgBVGP7pSWTUTsqX
nLRbwHOoq7hHwg==
-----END CERTIFICATE-----
)EOF";
X509List caCertList(caCert);
// Use secure client to handle TLS connection.
WiFiClientSecure wifiClient ;
PubSubClient mqttClient(wifiClient) ;
// BearSSL needs current time to validate certificate.
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", 0);
// Publish current time to MQTT every 5 seconds
#define MQTT_TIME_UPDATE_PERIOD 5000
unsigned long nextTimeUpdate = 0 ;
void mqttCallback(const char* topic, byte* payload, unsigned int length)
{
// Payload may not be null terminated.
char value[length+1];
memcpy(value,payload, length);
value[length] = '\0';
Serial.print("MQTT update: ");
Serial.print(topic);
Serial.print(":");
Serial.println(value);
}
void connectToWifi()
{
WiFi.mode(WIFI_STA);
WiFi.disconnect();
WiFi.begin(wifiSid.c_str(), wifiPwd.c_str());
Serial.println("");
Serial.print("Connecting to " + wifiSid + " - ");
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(1000);
}
Serial.println("");
Serial.print("Connected, IP Address = ");
Serial.println(WiFi.localIP());
}
void checkWifi()
{
if ( WiFi.status() != WL_CONNECTED )
{
connectToWifi();
}
}
void checkMQTT()
{
if ( !mqttClient.connected() )
{
String details = MQTT_HOST + "/" ;
details += MQTT_PORT ;
Serial.println("Connecting to MQTT server: " + details);
mqttClient.setServer(MQTT_HOST.c_str(), MQTT_PORT);
while( !mqttClient.connected() )
{
Serial.println(".");
// secure client needs to know the current time.
timeClient.update();
time_t now = (time_t) timeClient.getEpochTime();
wifiClient.setX509Time(now);
int ret = mqttClient.connect(MQTT_CLIENT_ID.c_str(), MQTT_USER.c_str(), MQTT_PWD.c_str());
Serial.print("MQTT Connect returned: ");
Serial.println(ret);
if ( !mqttClient.connected() )
delay(5000);
}
Serial.println("Connected to MQTT");
mqttClient.setCallback(mqttCallback);
mqttClient.subscribe("test/value1");
}
}
void setup() {
Serial.begin(9600);
Serial.println("Starting");
// Load certificates
wifiClient.setTrustAnchors(&caCertList);
connectToWifi();
checkMQTT();
nextTimeUpdate = millis() + MQTT_TIME_UPDATE_PERIOD ;
}
void loop() {
checkWifi();
checkMQTT();
mqttClient.loop();
if ( millis() > nextTimeUpdate )
{
// publish the current time to MQTT.
timeClient.update();
const char* payload = timeClient.getFormattedTime().c_str();
mqttClient.publish("test/current-time", payload, true);
nextTimeUpdate = millis() + MQTT_TIME_UPDATE_PERIOD ;
}
delay(50);
}

Arduino (ESP8266) with AWS: Cant setup SSL connection

Im using a standart ESP8266 (No NodeMCU) to connect with AWS:
and everything goes normally, I can upload the code to my module:
Im using the libraries 2.5 for esp8266
I already did my part in AWS
/*
ESP8266 AWS IoT demo
Simple demo code to provide static data into AWS IoT platform
#include <ESP8266WiFi.h>
#include <AmazonIOTClient.h>
#include >
Esp8266HttpClient httpClient;
Esp8266DateTimeProvider dateTimeProvider;
AmazonIOTClient iotClient;
ActionError actionError;
const char* ssid = "Bra";
const char* password = "12345678";
void initWLAN()
{
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
}
}
void initAWS()
{
iotClient.setAWSRegion("us-east-2");
iotClient.setAWSEndpoint("amazonaws.com");
iotClient.setAWSDomain("QWERTYU");
iotClient.setAWSPath("/things/thingy/shadow");
iotClient.setAWSKeyID("XDDDDDD");
iotClient.setAWSSecretKey("XDDDDDDI");
iotClient.setHttpClient(&httpClient);
iotClient.setDateTimeProvider(&dateTimeProvider);
}
void setup() {
Serial.begin(115200);
delay(10);
Serial.println("begin");
initWLAN();
Serial.println("wlan initialized");
initAWS();
Serial.println("iot initialized");
}
void loop()
{
char shadow[100];
strcpy(shadow, "{\"state\":{\"reported\":{\"test_value1\":123, \"test_value2\":234}}}");
Serial.println("Trying to send data");
Serial.print(shadow);
char* result = iotClient.update_shadow(shadow, actionError);
Serial.print(result);
delay(10000);
}
It seems that everything works fine but, the module load perfect...
Im getting the error:
" can't setup SSL connection "
Any ideas? Honestly Im lost

AsyncUDP example on two ESP32s not working: "WL_NO_SSID_AVAIL"

I am attempting to create a direct Client-Server WiFi network between two ESP32 DEVKITV1s powered by my two computer's USB ports.
I have loaded the example using the Arduino IDE (with the additional boards manager URL https://dl.espressif.com/dl/package_esp32_index.json) and the WiFi status (on both boards) is WL_NO_SSID_AVAIL.
The client code:
#include "WiFi.h"
#include "AsyncUDP.h"
const char * ssid = "my_ssid";
const char * password = "my_password";
AsyncUDP udp;
void setup()
{
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println("WiFi Failed");
while(1) {
delay(1000);
}
}
if(udp.connect(IPAddress(192,168,1,100), 1234)) {
Serial.println("UDP connected");
udp.onPacket([](AsyncUDPPacket packet) {
Serial.print("UDP Packet Type: ");
Serial.print(packet.isBroadcast()?"Broadcast":packet.isMulticast()?"Multicast":"Unicast");
Serial.print(", From: ");
Serial.print(packet.remoteIP());
Serial.print(":");
Serial.print(packet.remotePort());
Serial.print(", To: ");
Serial.print(packet.localIP());
Serial.print(":");
Serial.print(packet.localPort());
Serial.print(", Length: ");
Serial.print(packet.length());
Serial.print(", Data: ");
Serial.write(packet.data(), packet.length());
Serial.println();
//reply to the client
packet.printf("Got %u bytes of data", packet.length());
});
//Send unicast
udp.print("Hello Server!");
}
}
void loop()
{
delay(1000);
//Send broadcast on port 1234
udp.broadcastTo("Anyone here?", 1234);
}
The server code:
#include "WiFi.h"
#include "AsyncUDP.h"
const char * ssid = "my_ssid";
const char * password = "my_password";
AsyncUDP udp;
void setup()
{
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println("WiFi Failed");
while(1) {
delay(1000);
}
}
if(udp.listen(1234)) {
Serial.print("UDP Listening on IP: ");
Serial.println(WiFi.localIP());
udp.onPacket([](AsyncUDPPacket packet) {
Serial.print("UDP Packet Type: ");
Serial.print(packet.isBroadcast()?"Broadcast":packet.isMulticast()?"Multicast":"Unicast");
Serial.print(", From: ");
Serial.print(packet.remoteIP());
Serial.print(":");
Serial.print(packet.remotePort());
Serial.print(", To: ");
Serial.print(packet.localIP());
Serial.print(":");
Serial.print(packet.localPort());
Serial.print(", Length: ");
Serial.print(packet.length());
Serial.print(", Data: ");
Serial.write(packet.data(), packet.length());
Serial.println();
//reply to the client
packet.printf("Got %u bytes of data", packet.length());
});
}
}
void loop()
{
delay(1000);
//Send broadcast
udp.broadcast("Anyone here?");
}
Has anyone else had problems running the example code on their ESP32 using the Arduino IDE?
In summary, my misunderstandings were:
The AsyncUDP example does not allow direct client-server communication. It requires an intermediary router, e.g. a home router. This is because of the WiFi.mode(WIFI_STA) setting - the server needed to be set to WiFi.mode(WIFI_AP) for other ESP32s to be connected to.
Both the client and server need to use the udp.listen(port) function to receive messages (where you can specify the port). To send messages, use udp.broadcast(message) for the server and udp.broadcastTo(message, port) for the client.
The following code is the smallest example I could make that still worked. I'm sure there are better examples available, but this is the way I got the example to work to communicate between the two ESP32s without HTTP requests, using an intermediary router, etc...
The client side:
#include "WiFi.h"
#include "AsyncUDP.h"
const char * ssid = "my_ssid";
const char * password = "my_password";
AsyncUDP udp;
int port = 1234;
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA); // Make this the client (the server is WIFI_AP)
WiFi.begin(ssid, password);
delay(100);
Serial.print("Connecting...");
// Display a period every 0.5 s to show the user something is happening.
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("");
if(udp.listen(port)) {
udp.onPacket([](AsyncUDPPacket packet) {
Serial.print("Received data: ");
Serial.write(packet.data(), packet.length());
Serial.println();
});
}
}
void loop(){
delay(1000);
udp.broadcastTo("A message for the server from the client.", port);
}
The server side:
#include "WiFi.h"
#include "AsyncUDP.h"
const char *my_ssid = "my_ssid";
const char *password = "my_password";
int port = 1234;
AsyncUDP udp;
void setup(){
Serial.begin(115200);
WiFi.mode(WIFI_AP);
WiFi.softAP(my_ssid, password);
delay(100);
if(udp.listen(port)) {
udp.onPacket([](AsyncUDPPacket packet) {
Serial.print("Data: ");
Serial.write(packet.data(), packet.length());
Serial.println();
});
}
}
void loop() {
delay(1000);
udp.broadcastTo("Anyone here? Love from the server.", port);
}
This is just a modest addition to Jeremy's answer.
The text states that server uses udp.broadcast(message) while the client uses udp.broadcastTo(message, port)
On the other hand, the provided code uses broadcastTo both sides.
I was wondering why that and after nosing around in the source code AsyncUPD.cpp I saw that udp.broadcast will actually do its job by calling udp.broadcastTo using as the second parameter the local port.
Refer to: https://github.com/espressif/arduino-esp32/blob/master/libraries/AsyncUDP/src/AsyncUDP.cpp line 809.
It is a minor detail but I think worth mentioning it. It allowed me to pair ESP32 boards of same type and (most important to me) using same code for the UDP iteractions. Hence, the two boards may work together (hierarchically or not) or autonomously.

How will USB get devices information

how can i in a UWP app get devices information connected via usb port ,at which port also. and how can i check in case of phone. can i also check that device external power source ,means device is charging via adapter or via usb cable .
You can check the remarks and code from here UsbDevice class
See the following code:
protected override async void OnLaunched1(LaunchActivatedEventArgs args)
{
UInt32 vid = 0x045E;
UInt32 pid = 0x078F;
string aqs = UsbDevice.GetDeviceSelector(vid, pid);
var myDevices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(aqs, null);
if (myDevices.Count == 0)
{
ShowError("Device not found!");
return;
}
UsbDevice device = await UsbDevice.FromIdAsync(myDevices[0].Id);
// Send a control transfer.
UsbSetupPacket initSetupPacket = new UsbSetupPacket()
{
Request = initRequest,
RequestType = new UsbControlRequestType() {
Recipient = UsbControlRecipient.DefaultInterface,
ControlTransferType = UsbControlTransferType.Vendor
}
};
await device.SendOutControlTransferAsync(initSetupPacket);
}
From which you can loop the deviceinformation for details. Please check if you can find the info you want.

UDP DatagramPacket not received from external client

I have a game with a UDP/TCP server and client. One UDP port (2406) for updating the client's location, and one TCP port (2407) for the chat. The problem here is at 2406.
When I play the clients in my local network, everything runs fine. But when an external client wants to join, I only receive the first package (the join command) and after that... nothing. I (logged in on local network) cannot see the external player. BUT they can see me. The chat works for both sides. So it's really related to the DatagramSocket. I'll try to post as much info as possible related to the UDP and not the TCP.
Anyone knows what the problem is here?
Ports are forwarded like UDP 2406, TCP 2407.
Server, sockets:
DatagramSocket socket = new DatagramSocket(2406, InetAddress.getLocalHost());
ServerSocket serversocket_chat = new ServerSocket(2407, 0, InetAddress.getLocalHost());
Server, receive thread:
byte[] buffer = new byte[1024];
DatagramPacket dp = new DatagramPacket(buffer, 1024);
while(true){
try{
this.socket.receive(dp);
String data = new String(dp.getData(), 0, dp.getLength()).trim();
String[] args = data.split(":");
String command = args[0];
String reply = null;
try{
reply = handleCommand(dp, command, args);
} catch( Exception e ){
System.err.println("Error while handling command: " + command);
e.printStackTrace();
}
if(reply != null){
reply += "\n";
DatagramPacket reply_packet = new DatagramPacket(reply.getBytes(), reply.length(), dp.getSocketAddress());
this.socket.send(reply_packet);
}
} catch (IOException e){
e.printStackTrace();
}
}
new Thread(chat_receive).start();
As soon as someone sends a message, the method handleCommand will find out what it is. Every message is a byte[] derived from a String. If the message is "cj:Hello", handleCommand finds command cs, username Hello. THIS is received by the server. After that, if that same person sends something, nothing will be received.
Client sockets:
private DatagramSocket socket;
private Socket socket_chat;
Client connecting:
this.socket = new DatagramSocket();
this.socket_chat = new Socket(ip, port+1);
Client sending:
private Runnable send = new Runnable() {
#Override
public void run() {
DatagramPacket dp;
String sendStringBuffered;
while(true){
if(sendString != null){
sendStringBuffered = sendString;
dp = new DatagramPacket(sendStringBuffered.getBytes(), sendStringBuffered.length(), ip, port);
try {
socket.send(dp);
} catch (IOException ex) {
Logger.getLogger(NewClient.class.getName()).log(Level.SEVERE, null, ex);
}
sendString = null;
}
}
}
};
Two things come into mind:
UDP is not reliable. A datagram may get lost at any time
UDP packets usually do no not traverse NATs just like that
For the sake of systematic troubleshooting, make sure the packets really get to their destination using a packet sniffer/analyzer (like tcpdump or wireshark)