How to send a packet from tcp server to client use nodemcu(ESP8266) in arduino IDE? - tcp

In this code I wrote that the server send again what it received from client:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <WiFiServer.h>
WiFiServer server(8080);
WiFiClient client;
void setup()
{
initHardware();
setupWiFi();
server.begin();
}
void loop()
{
if (!client.connected()) {
// try to connect to a new client
client = server.available();
} else {
// read data from the connected client
if (client.available() > 0) {
char inChar= client.read();
String in=(String) inChar;
Serial.print(in);
server.write(inChar);
}
}
}
void setupWiFi()
{
WiFi.mode(WIFI_AP_STA);
WiFi.softAP("esp", "123456789");
// WiFi.softAP("RControl", WiFiAPPSK);
}
void initHardware()
{
Serial.begin(115200);
}
Now it receive what I send from my PC, but it doesn't send anything to me.
Why? What is wrong here?

Related

Measure ESP32 CPU Utilization

I am communicating two ESP32 boards which are connected to a Wifi Network. One ESP32 board is the Server and the other is the client. I want to measure the ESP32 CPU utlization on the client ESP32. I have no idea how to do it and have not yet found any useful resources on the internet. Can someone help me with this?
This is the code on server
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
const char* ssid = "XXXXX";
const char* password = "XXXX";
AsyncWebServer server(80);
void setup() {
Serial.begin(115200);
WiFi.begin(ssid,password);
while (WiFi.status()!= WL_CONNECTED){
delay(200);
Serial.println("Connecting to Wifi...");
}
Serial.println("Connected to Wifi");
Serial.println(WiFi.localIP());
server.on("/test", HTTP_GET, [](AsyncWebServerRequest *request){
Serial.println("Request received from esp32client");
request->send(200, "text/plain", "Hello from ESP32Server to ESP32Client");
});
server.on("/test1", HTTP_GET, [](AsyncWebServerRequest *request){
Serial.println("Request received from PC-Client");
request->send(300, "text/plain", "Hello from ESP32Server to PC");
});
server.begin();
}
void loop() {
// put your main code here, to run repeatedly:
}
This is the code on Client
#include <WiFi.h>
#include <HTTPClient.h>
const char* ssid = "XXXXX";
const char* password ="XXXXX";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid,password);
while (WiFi.status()!= WL_CONNECTED){
delay(500);
Serial.println("Connecting to Wifi...");
}
Serial.println("Connected to Wifi Network...");
Serial.println(WiFi.localIP());
}
void loop() {
HTTPClient http;
http.begin("http://192.168.43.35/test");
int httpCode = http.GET();
if (httpCode > 0) {
String payload = http.getString();
Serial.println(httpCode);
Serial.println(payload);
}
else {
Serial.println("Error on HTTP request");
}
http.end();
delay(30000);
}
Use this function to get CPU load
vTaskGetRunTimeStats(char *buffer);
It tells CPU utilization by currently running task on esp32.
API documentation here.

Send data periodically as a server to my client in arduino ESP8226

I'm using NodeMCU board to communicate a laptop through WiFi. Basic communication is ok with a code like this:
void loop (){
WiFiClient client = server.available();
if (client) {
while (client.connected()){
client.println(Data_mem[0]);
delay(2000);
}
client.stop(); // tarminates the connection with the client
}
}
But when I want to send data a Timer Tick, it seems the client couldn't connect to me.
void setup(){
....
//Initialize Ticker every 40ms
Data_Rec.attach_ms(40, 40ms_Data );
}
void 40ms_Data (){
WiFiClient client = server.available();
Serial.println("40ms_Data A");
if (client) {
Serial.println("40ms_Data B");
if (client .connected()){
Serial.println("40ms_Data C");
client.println(40ms_Data [0]);
}
else{
client.stop();
}
}
}
I arduino serial monitor, i see only this:
40ms_Data A \r\n
40ms_Data A \r\n
....
So, could anyone help me? maybe it a problem of WiFiClient deceleration in a non-forever loop (like example 1). But I have no idea to fix it.
According to M.R.'s idea, this is my complete new code:
#include <ESP8266WiFi.h>
#include <Ticker.h>
/* Put your SSID & Password */
const char* ssid = "NodeMCU"; // Enter SSID here
const char* password = "12345678"; //Enter Password here
/* Put IP Address details */
IPAddress local_ip(192,168,1,1);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);
WiFiServer server(80);
const int CLIENT_TIMEOUT = 2000;
Ticker Data_Rec;
bool Sending_40ms_Start_Flag = false;
void setup() {
Serial.begin(115200);
pinMode(D0, OUTPUT);
WiFi.softAP(ssid, password);
WiFi.softAPConfig(local_ip, gateway, subnet);
delay(100);
server.begin();
Serial.println("HTTP server started");
Data_Rec.attach_ms(500, flag_enable);//500ms is for test
}
void flag_enable(){
//Read FPGA Data from SPI
//...
Sending_40ms_Start_Flag = true;
}
void loop(){
WiFiClient client = server.available();
if (client) {
while(client.connected()){
Serial.println("40ms_Data B");
if (Sending_40ms_Start_Flag){
client.println("Server listening.\r");
Sending_40ms_Start_Flag = false;
}
delay(1);//without this delay, ESP would be reset(because it cannot handle background processes)
}
// else{
// client.stop();
// }
}
}
This code worked. But the server RST the TCP connection after sending one,two or tree "Server listening." as Wireshark shows: Wireshark Capture
What is probable cause of TCP Reset from ESP?
Besides that some syntax errors in your code:
A good solution is to create a static pointer object from client and pass it as an argument to ms40_Data function:
void ms40_Data(WiFiClient *client)
{
Serial.println("40ms_Data A");
if (*client)
{
Serial.println("40ms_Data B");
if (client->connected())
{
Serial.println("40ms_Data C");
//client.println(40ms_Data [0]);
}
else
{
client->stop();
}
}
}
void setup()
{
...
// create a static object from WiFiClient
static WiFiClient client = server.available();
//Initialize Ticker every 40ms
Data_Rec.attach_ms(40, ms40_Data, &client);
}
void loop()
{
}
Another solution is, you can set a flag inside your ticker and then call your ms40_Data function:
bool start_40ms_Data = false;
void ms40_Data()
{
static WiFiClient client = server.available();
Serial.println("40ms_Data A");
if (client)
{
Serial.println("40ms_Data B");
if (client.connected())
{
Serial.println("40ms_Data C");
//client.println(40ms_Data [0]);
}
else
{
client.stop();
}
}
}
void flag_enable()
{
start_40ms_Data = true;
}
void setup()
{
...
//Initialize Ticker every 40ms
Data_Rec.attach_ms(40, flag_enable);
}
void loop()
{
if (start_40ms_Data)
{
ms40_Data();
start_40ms_Data = false;
}
}
The point is to adding this to setup function:
WiFi.mode(WIFI_AP);
Full explanation: Here
Thank you,

NodeMCU 1.0 (ESP-12E Module) as a TCP server

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
const char *ssid = "ESPap";
const char *password = "thereisnospoon";
WiFiServer server(8080);
void setup() {
delay(1000);
Serial.begin(115200);
Serial.println();
Serial.print("Configuring access point...");
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
server.begin();
}
void loop() {
WiFiClient clie = server.available();
if(clie) {
while(clie.connected()) {
if(clie.available()) {
Serial.println(clie.read());
}
}
clie.stop();
}
}
I'm new to IoT. My goal is to start a TCP server using NodeMCU 1.0 to listen to the string sent by an Android app. The Android app is already implemented and 100% working. (Tested using AT commands with an ESP8266-01 module).
But when I upload this code to the NodeMCU it doesn't print out the strings in the Serial Monitor.
What is wrong? There is no errors showing up either.
Did you try using clie.readString() or clie.readStringUntil() instead of clie.read().

Message is not publishing to ESP8266 from IBM Bluemix

I have programmed to my ESP8266 and subscribed one topic to keep listening messages. This is my graphical view of injecting message to IBM Iot node.
This is my settings of inject view
This is my settings of IBM Iot node.
Here are my logs at Serial Monitor, it is connected and subscribed to cmd channel
So far so good, When I am trying to inject a message to my IBM Iot node then it is not publishing a message, as it is not reaching on serial monitor and no log on debug view. here you can see
Here is source code:
#include <ESP8266WiFi.h>
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient/releases/tag/v2.3
const char* ssid = "shiv";
const char* password = "manmohan#12345";
#define ORG "2kafk4"
#define DEVICE_TYPE "ESP8266"
#define DEVICE_ID "5CCF7FEED6F0"
#define TOKEN "opKF7v3#8jRM*mGkb_"
char server[] = ORG ".messaging.internetofthings.ibmcloud.com";
char topic[] = "iot-2/cmd/test/fmt/String";
char authMethod[] = "use-token-auth";
char token[] = TOKEN;
char clientId[] = "d:" ORG ":" DEVICE_TYPE ":" DEVICE_ID;
WiFiClient wifiClient;
void callback(char* topic, byte* payload, unsigned int payloadLength) {
Serial.print("callback invoked for topic: "); Serial.println(topic);
for (int i = 0; i < payloadLength; i++) {
Serial.print((char)payload[i]);
}
}
PubSubClient client(server, 1883, callback, wifiClient);
void setup() {
Serial.begin(115200);
Serial.println();
wifiConnect();
mqttConnect();
}
void loop() {
if (!client.loop()) {
mqttConnect();
}
}
void wifiConnect() {
Serial.print("Connecting to "); Serial.print(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.print("nWiFi connected, IP address: "); Serial.println(WiFi.localIP());
}
void mqttConnect() {
if (!client.connected()) {
Serial.print("Reconnecting MQTT client to "); Serial.println(server);
while (!client.connect(clientId, authMethod, token)) {
Serial.print(".");
delay(500);
}
initManagedDevice();
Serial.println();
}
}
void initManagedDevice() {
if (client.subscribe(topic)) {
Serial.println("subscribe to cmd OK");
} else {
Serial.println("subscribe to cmd FAILED");
}
}
I tried to check cloud foundry logs using cf command, here it is https://pastebin.com/dfMaS1Gd
Can anyone hint me what I am doing wrong ? Thanks in advance.
Confirm the device type is correctly specified in your node configuration. Currently the screenshot show 0.16.2 which doesn't seem to match the device type you registered and what is specified in your code.

Send get request with arduino to ASP.NET webservice

I created a webservices in ASP .NET, that i published on azure, with this function
public string GetObject(int id)
{
return ("it is a test !");
}
when i enter the right URL, it works.
But when i try to send the request with arduino (based on ethernetclient example), it does not work.
the arduino code :
#include "Arduino.h"
#include <SPI.h>
#include <WiFlyHQ.h>
#include <Ethernet.h>
#include <SoftwareSerial.h>
WiFly wifly;
char ssid[] = "myssid";
char password[] = "mypass";
void setup() {
Serial.begin(9600);
wifly.begin(&Serial, NULL);
if (!(wifly.setSSID(ssid))) {
Serial.println("Fail to set ssid");
}
/* if (!(wifly.setKey(password))) {
Serial.println("Fail to set passPhrase");
} */
if (!(wifly.setPassphrase(password))) {
Serial.println("Fail to set passPhrase");
}
wifly.enableDHCP();
if (wifly.join()) {
Serial.println("Joined wifi network");
} else {
Serial.println("Failed to join wifi network");
}
if (wifly.open(myurl.azurewebsites.net)) {
wifly.println("GET /api/object/123 HTTP/1.0");
wifly.println("");
}
else
Serial.println("Connection failed");
}
void loop() {
if (client.available()) {
char c = client.read();
Serial.print(c);
}
}
The connection to the ssid works. But it blocks on wifly.open(). But, if I put wifly.open("search.yahoo.com") and then wifly.write("GET /search?p=50+km+in+miles HTTP/1.0"), ALL WORKS !
Do you know why ?
Thanks for your help.
How does EthernetClient get connected with WiFly? I don't see any calls that connect them. I have done some playing with a WiFly module but I don't see how you use EthernetClient with it.
The WiFly module is the network connection and is accessed via serial. Wouldn't you need to make the request though it, handle the responses with serial processing?

Resources