Ethernet Shield Not Appearing on Network - server

I am currently working on a project that involves an arduino uno and an ethernet shield. I am using a sketch from Randomnerdtutorials.com (with slight changes to fit my router) which I will provide. The server that the ethernet shield creates does show up and work when I put the IP address in the URL bar (192.168.1.178:8080) The ethernet shield itself however does not show up on my list of attached devices to my Netgear router. It does occasionally but then disappears. Any ideas? I looked at another thread that stated to replace
Ethernet.begin(mac, ip, gateway, subnet);
with
Ethernet.begin(mac);
but that did not work. Any ideas are welcome. Here is the full code
/*
Created by Rui Santos
Visit: http://randomnerdtutorials.com for more arduino projects
Arduino with Ethernet Shield
*/
#include <SPI.h>
#include <Ethernet.h>
#include <Servo.h>
int led = 4;
Servo microservo;
int pos = 0;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
byte ip[] = { 192, 168, 1, 178 }; // ip in lan (that's what you need to use in your browser. ("192.168.1.178")
byte gateway[] = { 192, 168, 1, 130 }; // internet access via router
byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
EthernetServer server(8080); //server port
String readString;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
pinMode(led, OUTPUT);
microservo.attach(7);
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip, gateway, subnet);
// Ethernet.begin(mac);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}
void loop() {
// Create a client connection
EthernetClient client = server.available();
if (client) {
while (client.connected()) {
if (client.available()) {
char c = client.read();
//read char by char HTTP request
if (readString.length() < 100) {
//store characters to string
readString += c;
//Serial.print(c);
}
//if HTTP request has ended
if (c == '\n') {
Serial.println(readString); //print to serial monitor for debuging
client.println("HTTP/1.1 200 OK"); //send new page
client.println("Content-Type: text/html");
client.println();
client.println("<HTML>");
client.println("<HEAD>");
client.println("<meta name='apple-mobile-web-app-capable' content='yes' />");
client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />");
client.println("<link rel='stylesheet' type='text/css' href='http://randomnerdtutorials.com/ethernetcss.css' />");
client.println("<TITLE>Random Nerd Tutorials Project</TITLE>");
client.println("</HEAD>");
client.println("<BODY>");
client.println("<H1>Random Nerd Tutorials Project</H1>");
client.println("<hr />");
client.println("<br />");
client.println("<H2>Arduino with Ethernet Shield</H2>");
client.println("<br />");
client.println("Turn On LED");
client.println("Turn Off LED<br />");
client.println("<br />");
client.println("<br />");
client.println("Rotate Left");
client.println("Rotate Right<br />");
client.println("<p>Created by Rui Santos. Visit http://randomnerdtutorials.com for more projects!</p>");
client.println("<br />");
client.println("</BODY>");
client.println("</HTML>");
delay(1);
//stopping client
client.stop();
//controls the Arduino if you press the buttons
if (readString.indexOf("?button1on") >0){
digitalWrite(led, HIGH);
}
if (readString.indexOf("?button1off") >0){
digitalWrite(led, LOW);
}
if (readString.indexOf("?button2on") >0){
for(pos = 0; pos < 180; pos += 3) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
microservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
if (readString.indexOf("?button2off") >0){
for(pos = 180; pos>=1; pos-=3) // goes from 180 degrees to 0 degrees
{
microservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
//clearing string for next read
readString="";
}
}
}
}
}

Looks like the problem is with DHCP. Try
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// try to congifure using IP address instead of DHCP:
Ethernet.begin(mac, ip);
}
else{Serial.println("DHCP OK!");
and see if it gives DHCP failure

Related

Can't get Adafruit MusicMaker and Ethernet to work at the same time

Working on an IoT project.
Environment:
Adafruit Feather M4 Express
Adafruit MusicMaker FeatherWing (amplified, this is a VS1053 at heart)
Silicognition PoE FeatherWing (electrically compatible with the Adafruit Ethernet FeatherWing)
PlatformIO with Visual Studio Code on a Mac (all libraries are up-to-date)
The Problem:
I can get either the Ethernet to work or the MusicMaker to work, but not both at the same time.
There are no errors during initialization, they just don't work.
Specifically, the MusicMaker's sineTest() method doesn't generate any sound if Ethernet has been initialized. Likewise, the Ethernet client's connect() method is unable to connect if the MusicMaker is initialized. Both methods work fine if the other device hasn't been initialized.
Feather Pins:
Purpose Pin
-------------------------- ---
VS1053 Chip select 6
VS1053 Data/command select 10
VS1053 Data request 9
SD Card Chip select 5
Ethernet Chip select 14
Note that I'm not currently using the SD card and haven't called its begin() method.
Note also that the Ethernet chip select is on a non-standard pin because the default conflicts with the VS1053 data/command select.
Also, the PoE FeatherWing has an EEPROM on it with a unique MAC address and reading this works fine.
One other note: I thought that I had this combination working in an earlier prototype a few months ago, but that may have been with the Feather 32U4.
TIA.
The prototype code:
#include <Arduino.h>
#include <Adafruit_VS1053.h>
#include <Ethernet.h>
#include <IPAddress.h>
#include <SPI.h>
#include <Wire.h>
//
// Pins for the Ethernet and MusicMaker FeatherWings.
// NOTE: These definitions assume a Feather M4 Express with a PoE FeatherWing
// modified to have its chip select on pin 14 because the default conflicts
// with the MusicMaker's DCS pin.
//
#define VS1053_CS 6 // VS1053 chip select pin (output)
#define VS1053_DCS 10 // VS1053 Data/command select pin (output)
#define SD_CARD_CS 5 // Card chip select pin
#define VS1053_DREQ 9 // VS1053 Data request, ideally an Interrupt pin
#define ETHERNET_CS 14 // Ethernet chip select pin. Note that this is custom because the default conflicts with VS1053_DCS.
//
// PoE FeatherWing.
//
#define MAC_EEPROM_I2C_ADDRESS 0x50 // I2C address of the 24AA02E48 EEPROM chip that contains our MAC address (on the PoE FeatherWing).
#define MAC_EEPROM_REGISTER 0xFA // Register within the 24AA02E48 that contains the first byte of our MAC address.
#define HANG while( true ){ delay( 10 ); }
IPAddress host = { 172, 24, 110, 1 };
uint16_t port = 8000;
const char* path = "/sounds/DingDong.mp3";
Adafruit_VS1053 player{ Adafruit_VS1053( -1, VS1053_CS, VS1053_DCS, VS1053_DREQ ) };
EthernetClient client;
uint8_t mp3Buf[VS1053_DATABUFFERLEN];
uint32_t contentLength;
byte macAddress[6]{};
uint32_t beginRequest();
void readMacAddress( byte* );
void setup()
{
Serial.begin( 115200 );
while( !Serial ){ delay( 10 ); }
Serial.println( "MusicMaker/Ethernet Prototype" );
Wire.begin();
Ethernet.init( ETHERNET_CS );
readMacAddress( macAddress );
if( !Ethernet.begin( macAddress ))
{
Serial.printf( "Unable to initialize the network; hardware status is %d\n",
Ethernet.hardwareStatus());
HANG;
}
Serial.print( "Mac address: " );
for( int ii = 0; ii < 6; ii++ )
{
if( macAddress[ii] < 16 ) { Serial.print( '0' ); }
Serial.print( macAddress[ii], HEX );
if( ii < 5 ) { Serial.print( ':' ); }
}
Serial.println();
Serial.print( "DNS IP: " ); Serial.println( Ethernet.dnsServerIP());
Serial.print( "Local IP: " ); Serial.println( Ethernet.localIP());
Serial.print( "Gateway IP: " ); Serial.println( Ethernet.gatewayIP());
Serial.print( "Subnet mask: " ); Serial.println( Ethernet.subnetMask());
if( !player.begin())
{
Serial.println( "Unable to initialize the MusicMaker" );
HANG;
}
Serial.println( "Initialized the MusicMaker" );
player.setVolume( 40, 40 );
player.sineTest( 0x44, 1000 ); // 1KHz tone for one second.
contentLength = beginRequest();
Serial.printf( "HTTP content length: %d\n", contentLength );
}
void loop()
{
if( player.readyForData())
{
if( client.available() > 0 )
{
uint8_t bytesRead = client.read( mp3Buf, VS1053_DATABUFFERLEN );
if( bytesRead > 0 )
{
player.playData( mp3Buf, bytesRead );
contentLength -= bytesRead;
if( contentLength <= 0 )
{
Serial.println( "That should be all of our sound" );
}
}
}
}
}
uint32_t beginRequest()
{
if( !client.connect( host, port ))
{
Serial.print( "Unable to connect to " );
Serial.print( host ); Serial.print( ':' ); Serial.println( port );
HANG;
}
Serial.print( "GET " ); Serial.print( path ); Serial.print( " HTTP/1.1\r\n" );
Serial.print( "Host: " ); Serial.print( host ); Serial.print( "\r\n" );
Serial.print( "Connection: close\r\n\r\n" );
client.print( "GET " ); client.print( path ); client.print( " HTTP/1.1\r\n" );
client.print( "Host: " ); client.print( host ); client.print( "\r\n" );
client.print( "Connection: close\r\n\r\n" );
char http[] = "HTTP/";
client.find( http ); // Skip over the HTTP/ part of the header.
client.parseFloat( SKIP_WHITESPACE ); // Skip over the HTTP version number.
int httpStatus = client.parseInt( SKIP_WHITESPACE );
if( httpStatus < 200 || httpStatus > 299 )
{
Serial.printf( "GET request failed; HTTP status is %d\n", httpStatus );
client.stop();
HANG;
}
char lengthHeader[] = "Content-Length:";
client.find( lengthHeader );
int contentLength = client.parseInt();
char endOfHeaders[] = "\r\n\r\n";
if( !client.find( endOfHeaders ))
{
Serial.println( "Invalid HTTP response (missing trailing line endings)" );
client.stop();
HANG;
}
return contentLength;
}
void readMacAddress( byte* addr )
{
Wire.beginTransmission( MAC_EEPROM_I2C_ADDRESS );
Wire.write( MAC_EEPROM_REGISTER );
int failed = Wire.endTransmission();
if( failed )
{
Serial.printf( "Unable to retrieve MAC address; endTransmission returned %d\n", failed );
HANG;
}
byte* b = addr;
int bytesRead = Wire.requestFrom( MAC_EEPROM_I2C_ADDRESS, 6 );
if( bytesRead < 6 )
{
Serial.printf( "Unable to retrieve MAC address; fewer than six bytes\n" );
HANG;
}
while( Wire.available())
{
*b++ = Wire.read();
}
}
Turned out to be a hardware problem.
The PoE FeatherWing's default CS pin conflicts with the MusicMaker's DCS pin. The PoE CS pin can be changed by cutting a trace on the back of the board and bodging a wire from a pad to whatever pin you want to use instead. I had done that.
Turns out though, that I hadn't cut it completely. This was causing the Ethernet library to pull the MusicMaker DCS low every time it pulled the Ethernet CS low.
I finally figured it out when I hooked up a logic analyzer to all of the CS pins and the SPI pins. It was very clear that MusicMaker DCS was going low with Ethernet CS.
Yay Logic Analyzer.

Using both TCP and UDP protocols seem not to work on Ethernet Shield w5100

I'm having a problem using both TCP and UDP in the same sketch. What appears to happen is that if the same socket is reused for UDP after it was in use for TCP, UPD fails to receive data. I was able to reproduce this with the WebServer example. I've added to it a DNS query once in every 10 seconds to query yahoo.com IP address. The DSN queries succeed if I'm not creating any client traffic from the browser. After I query the server over HTTP over TCP, the DSN queries start to fail. DNS queries are implemented in UDP. This is the code that I'm using:
/*
Web Server
A simple web server that shows the value of the analog input pins.
using an Arduino Wiznet Ethernet shield.
Circuit:
* Ethernet shield attached to pins 10, 11, 12, 13
* Analog inputs attached to pins A0 through A5 (optional)
created 18 Dec 2009
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe
modified 02 Sept 2015
by Arturo Guadalupi
*/
#include <SPI.h>
#include <Ethernet.h>
#include <Dns.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 177);
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
unsigned long t0;
void setup() {
// You can use Ethernet.init(pin) to configure the CS pin
//Ethernet.init(10); // Most Arduino shields
//Ethernet.init(5); // MKR ETH shield
//Ethernet.init(0); // Teensy 2.0
//Ethernet.init(20); // Teensy++ 2.0
//Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet
//Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println("Ethernet WebServer Example");
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
// Check for Ethernet hardware present
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
while (true) {
delay(1); // do nothing, no point running without Ethernet hardware
}
}
if (Ethernet.linkStatus() == LinkOFF) {
Serial.println("Ethernet cable is not connected.");
}
// start the server
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
t0 = millis();
}
void loop() {
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close"); // the connection will be closed after completion of the response
client.println("Refresh: 5"); // refresh the page automatically every 5 sec
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
// output the value of each analog input pin
for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
int sensorReading = analogRead(analogChannel);
client.print("analog input ");
client.print(analogChannel);
client.print(" is ");
client.print(sensorReading);
client.println("<br />");
}
client.println("</html>");
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
} else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
Serial.println("client disconnected");
}
if (millis() - t0 > 10000)
{
DNSClient dns;
dns.begin(IPAddress(8,8,8,8));
IPAddress yahoo;
if (dns.getHostByName("yahoo.com", yahoo) == 1)
{
Serial.print("Yahoo: ");
Serial.print(yahoo[0]);
Serial.print(".");
Serial.print(yahoo[1]);
Serial.print(".");
Serial.print(yahoo[2]);
Serial.print(".");
Serial.println(yahoo[3]);
}
else
{
Serial.println("Failed to query yahoo.com IP address");
}
t0 = millis();
}
}
Is this a known issue? Can someone please help in identifying the problem in my code, or if there is a workaround for this issue? Can it be a hardware issue? I'm using SunFounder boards, not the original Arduino boards.
Thanks a lot,
Boaz,

Running WebServerSecure and PubSubClient on ESP8266

I wrote a sketch for ESP8266. This sketch reads some sensor data and published it via MQTT. In addition I want to let a Web server provide the same data as HTML, or JSON web service.
The MQTT publish is triggered via a TaskScheduler timer.
Both functions, MQTT and Web server, work for itself, but sadly not together. Here's a simplified sketch:
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <ESP8266WebServerSecure.h>
#include <PubSubClient.h>
#include <TaskScheduler.h>
#include <My_WLAN.h> // provices connection to local WLAN and network settings
const char DNS_NAME[] = "myserver.local";
const int HTTPS_PORT = 443; // HTTPS
const char MQTT_SVR[] = "myserver.local";
const unsigned int MQTT_PORT = 8883; // MQTTS
WiFiClientSecure wifiClient;
PubSubClient mqttClient(wifiClient); // MQTT client instance
ESP8266WebServerSecure server(HTTPS_PORT); // web server instance
void t1Callback(void); // callback method prototypes
Task t1(60000, TASK_FOREVER, &t1Callback); // main loop task
Scheduler timer; // task scheduler
static const uint8_t SVR_FINGERPRINT[20] PROGMEM = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20 };
static const char deviceCert[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
[... certificate ...]
-----END CERTIFICATE-----
)EOF";
static const char deviceKey[] PROGMEM = R"EOF(
-----BEGIN RSA PRIVATE KEY-----
[... key ...]
-----END RSA PRIVATE KEY-----
)EOF";
/* *****************************
MQTT_connect
* *****************************/
void MQTT_connect()
{
int attempt = 0;
/* loop until reconnected */
while (!mqttClient.connected() && attempt < 10) {
attempt++;
Serial.print("Attempting MQTT connection ("); Serial.print(attempt); Serial.print(")...");
mqttClient.setServer(MQTT_SVR, MQTT_PORT);
if (mqttClient.connect(DNS_NAME)) {
Serial.println("success");
} else {
Serial.print("failed, status code = "); Serial.print(mqttClient.state());
Serial.println(". - Try again in 5 seconds...");
delay(5000);
}
}
}
/* *****************************
Web Server handleRoot
* *****************************/
void handleRoot() {
digitalWrite(LED_BUILTIN, LOW); // on
Serial.println("WebServer ROOT");
server.send(200, "text/html", "WebServer ROOT");
digitalWrite(LED_BUILTIN, HIGH); // off
}
/* *****************************
Web Server handleNotFound
* *****************************/
void handleNotFound() {
digitalWrite(LED_BUILTIN, LOW); // on
String message = "File not found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
digitalWrite(LED_BUILTIN, HIGH); // off
}
/* *************************
MQTT_publish_something
* *************************/
void MQTT_publish_something() {
digitalWrite(LED_BUILTIN, LOW); // on
char payload[30] = "some_payload_data";
if (!mqttClient.publish("MQTT/Test", payload, true)) { // retain message
Serial.println("MQTT message lost!");
}
digitalWrite(LED_BUILTIN, HIGH); // off
}
/* *************************
t1: main timer (callback)
* *************************/
void t1Callback() {
my.WiFi_connect(); // check and re-connect to WLAN (in My_WLAN.h)
if (WiFi.status() == WL_CONNECTED) {
MQTT_connect();
MQTT_publish_something();
}
}
/* *************************
setup
* *************************/
void setup() {
pinMode(LED_BUILTIN, OUTPUT); // internal LED
digitalWrite(LED_BUILTIN, HIGH); // off
/* -----------------------
open Serial |
----------------------- */
Serial.begin(74880);
while (!Serial); // wait for Serial being ready
/* -----------------------
connect to WLAN |
----------------------- */
my.WiFi_connect(); // this is connecting to WLAN & error handling (in My_WLAN.h)
wifiClient.setFingerprint(SVR_FINGERPRINT);
/* -----------------------
set mDNS |
----------------------- */
if (MDNS.begin(DNS_NAME)) {
Serial.printf("mDNS responder started for %s\n", DNS_NAME);
MDNS.addService("https", "tcp", HTTPS_PORT); // add service to MDNS-SD
MDNS.addService("mqtt", "tcp", MQTT_PORT);
} else
Serial.println("Error setting up mDNS responder!");
/* -----------------------
start HTTPS server |
----------------------- */
server.getServer().setRSACert(new X509List(deviceCert), new PrivateKey(deviceKey));
server.on("/", handleRoot); // standard HTML root
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTPS server started.");
Serial.println();
/* -----------------------
start timer |
----------------------- */
timer.init();
timer.addTask(t1);
// line 177:
timer.enableAll();
}
void loop() {
MDNS.update();
// line 184:
server.handleClient();
mqttClient.loop();
timer.execute();
}
Running MQTT only works fine and publishes data (I use the mosquitto broker).
Running the Web server (https://...) works fine as well, if commenting out line 177 (so MQTT does not get triggered).
With both functions active, as soon as the first MQTT message had been sent, the web server does not answer any more. I get PR_END_OF_FILE_ERROR in FF and ERR_CONNECTION_CLOSED in Chrome.
I guess, that these libraries somehow mess with each other, or that something confuses with the certificates. However, the fingerprint belongs to the server running mosquitto, while the X509 certificate belongs to the web server running on the ESP8266. These are two different machines and have nothing to do with each other.
Any idea welcome.
I suspect both libraries use port 443, and you can only have one listener on a given port. I've tried creating a BearSSL::ESP8266WebServerSecure object with alternate ports, such as 80 and 8443 but can't get them to work. Worse, there doesn't seem to be a way to stop a listener once a BearSSL::ESP8266WebServerSecure object has started, so it can't be released for later reuse.
I ended up using HTTP to get WiFi credentials, then HTTPS from there on out. Not a very satisfactory solution but it works.
Update: I was able to run a provisioning server on port 443, stop it by calling
BearSSL::ESP8266WebServerSecure provisioningServer(443);
BearSSL::ESP8266WebServerSecure server(443);
provisioningServer.close();
provisioningServer.~ESP8266WebServerSecure(); // note: cannot use TLS on both servers without this line
After calling the provisioning server's destructor I was able to start my server on port 443.

Unable to send publish messages from esp8266 to Raspberry (Broker) using MQTT. Getting Socket Error <Random Device Id>, Disconnecting

I am trying to send and receive a messages from Raspberry Pi (Broker) to Arduino-ESP8266 (client) using MQTT. What I am trying to achieve is pretty basic for now. The broker sends a start command and the client on receving the message should send back a random number. I am able to read the message sent by the broker but the messages from the client are never sent. Here is the code that I am using
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(19, 18); //RX, TX
#endif
#define MQTT_KEEPALIVE 10
#include <PubSubClient.h>
IPAddress server(192, 168, 0, 105);
char ssid[] = "user1956";
char password[] = "******";
int status = WL_IDLE_STATUS; //wifi radio's status
//MQTT
//const char* mqtt_topic = "Rpi_Master";
const char* mqtt_username = "pi";
const char* mqtt_password = "********";
//client Id
const char* clientID = "A_2";
//Variables for numbers
long randNumber1;
String rn1;
char rn1_char[50];
WiFiEspClient wifiClient;
PubSubClient client(wifiClient); //1883 is the listener port for the broker
void setup() {
// Initilize serial for debugging
Serial.begin(115200);
//initilize serial for ESP module
Serial1.begin(115200);
//initilize the ESP module
WiFi.init(&Serial1);
if (WiFi.status() == WL_NO_SHIELD)
{
Serial.println("WiFi shield not present");
while (true);
}
while (status != WL_CONNECTED)
{
Serial.print("Attempting to connect to WPA SSID : ");
Serial.println(ssid);
status = WiFi.begin(ssid, password);
}
Serial.println("You are connected to the network");
client.setServer(server, 1883);
client.setCallback(callback);
//Allow the hardware to sort itself
delay(1500);
randomSeed(50);
}
void callback(char* topic, byte* payload, unsigned int length)
{
Serial.print("Message Received: [");
Serial.print(topic);
Serial.println("]");
Serial.print("Message is:");
String message = (char *)payload;
Serial.println(message);
else if (!strncmp((char *)payload, "B1", length)) //Start code can be changed to any string value in place of 1
{
client.publish("Ad_B", "OK");
generateRandomData();
}
else if (!strncmp((char *)payload, "B2", length)) //Start code can be changed to any string value in place of 1
{
client.publish("Ad_B", "OK");
generateRandomData();
}
}
void loop()
{
if (!client.connected())
{
reconnect();
}
client.loop();
delay(1000);
}
void reconnect()
{
while (!client.connected())
{
Serial.print("Attempting MQTT Connection...");
//Attempt to Connect
if (client.connect(clientID, mqtt_username, mqtt_password))
{
Serial.println("connected");
//Once connected publish an announcement
client.publish("Ad_B", "Ready");
//and resubscribe
client.subscribe("Rpi_Master"); //This name can be changed
}
else
{
Serial.print("failed, rc = ");
Serial.print(client.state());
Serial.println("Trying again in 5 seconds");
//Wait for 5 seconds before retrying
delay(5000);
}
}
}
void generateRandomData(){
randNumber1 = random(0,0); //(14000,15000)
//Serial.println(randNumber1); // print a random number from 0to 299
rn1 = String(randNumber1);
rn1.toCharArray(rn1_char, rn1.length() + 1);
client.publish("LC_B_1", rn1_char);
client.publish("Ad_B", "End");
}
This is the output of the serial monitor that I am receiving:
07:45:42.016 -> [WiFiEsp] Initializing ESP module
07:45:45.430 -> [WiFiEsp] Initilization successful - 1.5.4
07:45:45.430 -> Attempting to connect to WPA SSID : No Free Wifi
07:45:50.464 -> [WiFiEsp] Connected to No Free Wifi
07:45:50.464 -> You are connected to the network
07:45:51.940 -> Attempting MQTT Connection...[WiFiEsp] Connecting to 192.168.0.105
07:45:52.084 -> connected
07:46:31.926 -> Message Received: [Rpi_Master]
07:46:31.926 -> Message is:B2ter
07:46:37.438 -> [WiFiEsp] TIMEOUT: 20
08:20:58.967 -> [WiFiEsp] >>> TIMEOUT >>>
The client is unable to publish any messages. The mosquitto log shows PINGREQ and RINGRESP to a random id and client.publish stops with the following message in the log - Socket Error on Client <Some Random Client Id>, Disconnecting. Attached the screenshot of the log. Is there any way to know what the unknown client is? Please help me to sort this issue. Thanks.
You generateRandom() function blocks (15 seconds) for longer than the keep alive (10 seconds) timeout and this will block the client.loop() function so it will not be able to send keep alive packets.

Linux TCP socket timestamping option

Quoting form this online kernel doc
SO_TIMESTAMPING
Generates timestamps on reception, transmission or both. Supports
multiple timestamp sources, including hardware. Supports generating
timestamps for stream sockets.
Linux supports TCP timestamping, and I tried to write some demo code to get any timestamp for TCP packet.
The server code as below:
//Bind
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
{
perror("bind failed. Error");
return 1;
}
puts("bind done");
//Listen
listen(socket_desc , 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
int c = sizeof(struct sockaddr_in);
client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c);
if (client_sock < 0)
{
perror("accept failed");
return 1;
}
// Note: I am trying to get software timestamp only here..
int oval = SOF_TIMESTAMPING_RX_SOFTWARE | SOF_TIMESTAMPING_SOFTWARE;
int olen = sizeof( oval );
if ( setsockopt( client_sock, SOL_SOCKET, SO_TIMESTAMPING, &oval, olen ) < 0 )
{ perror( "setsockopt TIMESTAMP"); exit(1); }
puts("Connection accepted");
char buf[] = "----------------------------------------";
int len = strlen( buf );
struct iovec myiov[1] = { {buf, len } };
unsigned char cbuf[ 40 ] = { 0 };
int clen = sizeof( cbuf );
struct msghdr mymsghdr = { 0 };
mymsghdr.msg_name = NULL;
mymsghdr.msg_namelen = 0;
mymsghdr.msg_iov = myiov;
mymsghdr.msg_iovlen = 1;
mymsghdr.msg_control = cbuf;
mymsghdr.msg_controllen = clen;
mymsghdr.msg_flags = 0;
int read_size = recvmsg( client_sock, &mymsghdr, 0);
if(read_size == 0)
{
puts("Client disconnected");
fflush(stdout);
}
else if(read_size == -1)
{
perror("recv failed");
}
else
{
struct msghdr *msgp = &mymsghdr;
printf("msg received: %s \n",(char*)msgp->msg_iov[0].iov_base);// This line is successfully hit.
// Additional info: print msgp->msg_controllen inside gdb is 0.
struct cmsghdr *cmsg;
for ( cmsg = CMSG_FIRSTHDR( msgp );
cmsg != NULL;
cmsg = CMSG_NXTHDR( msgp, cmsg ) )
{
printf("Time GOT!\n"); // <-- This line is not hit.
if (( cmsg->cmsg_level == SOL_SOCKET )
&&( cmsg->cmsg_type == SO_TIMESTAMPING ))
printf("TIME GOT2\n");// <-- of course , this line is not hit
}
}
Any ideas why no timestamping is available here ? Thanks
Solution
I am able to get the software timestamp along with hardware timestamp using onload with solarflare NIC.
Still no idea how to get software timestamp alone.
The link you gave, in the comments at the end, says:
I've discovered why it doesn't work. SIOCGSTAMP only works for UDP
packets or RAW sockets, but does not work for TCP. – Gio Mar 17 '16 at 9:331
it doesn't make sense to ask for timestamps for TCP, because there's
no direct correlation between arriving packets and data becoming
available. If you really want timestamps for TCP you'll have to use
RAW sockets and implement your own TCP stack (or use a userspace TCP
library). – ecatmur Jul 4 '16 at 10:39