Attempting MQTT connection...failed, rc=-2 try again in 5 seconds problem - mqtt

A month ago, I created a code and uploaded it to the NodeMCU (ESP8266) in which the NodeMCU establishes connection with the aREST.io MQTT broker. It worked properly.
The code:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <aREST.h>
WiFiClient espClient;
PubSubClient client(espClient);
aREST rest = aREST(client);
char* key = "the api key in aREST account";
const char* ssid = "SSID";
const char* password = "Pass";
#define trigger 5
#define echo 4
float distance;
void callback(char* topic, byte* payload, unsigned int length);
void setup(void)
{
Serial.begin(115200);
pinMode(trigger, OUTPUT);
pinMode(echo, INPUT);
rest.setKey(key);
client.setCallback(callback);
rest.variable("distance",&distance);
rest.set_name("esp8266");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
}
void loop() {
rest.handle(client);
digitalWrite(trigger, HIGH);
delayMicroseconds(10);
digitalWrite(trigger, LOW);
int timin = pulseIn(echo,HIGH);
distance = (171.5*((timin)))*10E-5;
delay(60);
rest.publish(client, "distance", distance, 60000);
}
void callback(char* topic, byte* payload, unsigned int length) {
rest.handle_callback(client, topic, payload, length);
}
At the moment, the ESP8266 can't connect to the broker. It prints the following message after it connects to WiFi on the serial monitor:
"Attempting MQTT connection...failed, rc=-2 try again in 5 seconds"
I checked the API key about 5 times. it's the right one
I analyzed the network with wireshark and obtained the following:
As shown in the photo, the ESP8266 sends a CONNECT data packet to the aREST broker. The broker responds with the CONNACK packet. It's repeated every 5 seconds the content in the CONNECT packet:
the content of the CONNACK:

I believe the issue may be that the broker is down.
Your code looks like a modified version of the 'ESP8266_cloud.ino' code found in the ArduionIDE examples. I have an ESP8266 D1 and ran that example code with my own API plugin from aREST.io and get the same error message as you.
Running example code 'mqtt_esp8266.ino' I see interaction with my board to the broker, so I don't have reason to believe there's a general hardware or connectivity issue outside of the aREST broker.
Digging into aREST.h, the MQTT broker/server is 'mqtt.arest.io'
Checking on https://downforeveryoneorjustme.com/mqtt.arest.io, they say it's down.
Sorry that's not more helpful :/
I tried contacting the developer/the aREST Instagram page and have yet to hear back. Will keep you posted - please update your findings as well!

Related

ESP8266 (Adafruit Huzzah) disconnects immediately from WiFi, STA disconnect: 203

I have a PM sensor, made for the initiative "sensor community", outside the window, attached to an ESP8266 which connected to a repeater that repeats my home network. Yesterday morning I noticed that suddenly it wasn't publishing the values anymore.
Today I reflashed the board, which is an Adafruit Huzzah with an ESP8266 on board, with the basic example WiFiClientBasic from the ESP82666 library switching on the serial debug of the WiFi.
void setup() {
Serial.begin(115200);
// We start by connecting to a WiFi network
WiFi.mode(WIFI_STA);
WiFiMulti.addAP(ssid, password);
Serial.println();
Serial.println();
Serial.print("Wait for WiFi... ");
while (WiFiMulti.run() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
delay(500);
}
The debug yields continuously this error:
[WIFI] Connecting BSSID: SSID: Channel: 6 (-39)
scandone
state: 0 -> 2 (b0)
state: 2 -> 3 (0)
state: 3 -> 0 (12)
wifi evt: 1
STA disconnect: 203
reconnect
scandone
state: 0 -> 2 (b0)
state: 2 -> 3 (0)
state: 3 -> 0 (12)
wifi evt: 1
STA disconnect: 203
reconnect
Another ESP8266 board (a LOLIN Wemos) that had the same configuration refuses to connect. Other devices connected to the same network (my 2 laptops, an Android tablet, a Raspberry Pi) don't have any troubles.
The repeater has a DHCP running and has no problem in releasing IP to other devices. Assigning the ESP8266 a static IP, both on the board and/or on the repeater, has no effect.
I'm not a network expert, but those are the main configs of the repeater (a rather old Digicom REW300).
WLAN STATUS Infrastructure Client --- (Connected)
Signal Strenght 54%
Channel-Band 2.4GHz (G+N) channel 6
Rate 13Mbps (MCS1)
Encryption WPA2-PSK
Repeater Status
WLAN STATUS AP --- (Enabled)
Rate auto
Encryption WPA2-PSK
I also looked at the log on the repeater:
Mar 19 16:01:12 DIGICOM-REW300-Z01 user.warn kernel: wlan0-vxd: A wireless client is deauthenticated - "MAC address of the ESP8266"
Mar 19 16:01:13 DIGICOM-REW300-Z01 user.warn kernel: wlan0-vxd: A wireless client is deauthenticated - "MAC address of the ESP8266"
Mar 19 16:01:15 DIGICOM-REW300-Z01 user.warn kernel: wlan0-vxd: A wireless client is deauthenticated - "MAC address of the ESP8266"
I didn't change the settings of the repeater recently, however yesterday morning the ISP changed the main router with a newer one. I think that could be the problem, but anyway the ESP8266 isn't connecting directly to it (it's too far away) but to the repeater which didn't change at all. Moreover: if I take the ESP8266 inside, it can connect to the main router without any troubles. It seems that the combination of new router and old repeater caused the problem, and just only for the ESP8266s. The only thing that changed from the old router is that the new one has only band G+N only, while the old one had B+G+N, I don't think it matters anyway, as it can be connected directly, and the old repeater is B+G+N.
The official docs from Espressif says that error 203 is ASSOC_FAIL, which is a rather generic error.
Further test I did: if the repeater is tethered with my mobile, the ESP8266 connects.
So:
ESP8266 to repeater to WAN (broken)
ESP8266 to WAN (OK)
ESP8266 to repeater to Mobile Phone to WAN (OK)
Maybe add these lines can help...
WiFi.setAutoReconnect(true);
WiFi.persistent(true);
Here an example with reconection and status connection

ESP8266 cannot reconnect to last saved WiFi network

I'm using WifiManager library to manually add user's network on configuration portal. Already it works fine, but every time I power off and power on again, it does not connect to network I have established previous. To connect I have to pin out the 'Vcc' of ESP8266 and pin in again and then again connect with ESP8266 network and go to configure portal.
For now I have two lines in code with 'WifiManager';
Good news is that connects to Wifi by configurationPortal.
ESP8266WebServer server; //server variable
void setup() {
initializePin(); //call function
Serial.begin(74880);
delay(500);
//Connect to network
WiFiManager wifiManager;
wifiManager.autoConnect("ESP8266","password");
Serial.println("Connected.");
if (!MDNS.begin("esp8266")) { Serial.println("Error setting up MDNS responder!"); }
else { Serial.println("mDNS responder started"); }
serverSection();
server.begin();
Serial.println("Server started");
}
I need to connect to previous established network,
Also it would be fine to run Configuration Portal if there wont be connection to that network ( for example if device would be transfer to other place)
Your code is supposed to connect to the internet. What happens usually when you use auto connect and it fails is that WL_IDLE_STATUS occurs. Read more about it here: https://www.arduino.cc/en/Reference/WiFiStatus . What I would do is to check if I got that status then I would try to reconnect to the wifi with a delay of 2 seconds. Here is an example:
if (WiFi.status() == WL_IDLE_STATUS) {
delay(2000);
WiFi.begin("yourssid", "password");
}

ESP8266: Wifi gets connected, but no internet access

I am trying to connect my ESP8266 NodeMCU to my Mobile Hotspot Wifi
When I try to connect to the ESP Wifi using laptop, It says Wifi Connected, no Internet access.
Which means, The Wifi_SSID and Password are fetched by ESP correctly.
Why is the ESP not able to connect to the Internet?
I have used Arduino IDE for uploading code to ESP8266.
I have uploaded the below code to the ESP8266.
#include <FirebaseArduino.h>
#include <ESP8266WiFi.h>
// Set these to run example.
#define WIFI_SSID "OnePlus3"
#define WIFI_PASSWORD ""
#define FIREBASE_DB_URL "https://my_db_url.firebaseio.com/"
#define FIREBASE_DB_SECRET_KEY "fakezaSyDsdadasddwGClaAy8ltYgywwo6i_VzXgY"
void setup() {
Serial.begin(115200);
pinMode(D1, OUTPUT);
pinMode(D2, OUTPUT);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
Firebase.begin(FIREBASE_DB_URL, FIREBASE_DB_SECRET_KEY);
Firebase.stream("/automation");
}
void loop() {
if (Firebase.failed()) {
Serial.println("streaming error");
Serial.println(Firebase.error());
}
if (Firebase.available()) {
FirebaseObject event = Firebase.readEvent();
String eventType = event.getString("type");
eventType.toLowerCase();
Serial.print(eventType);
if (eventType == "put") {
String path = event.getString("path");
String data = event.getString("data");
if (path.equals("/fan/value")) {
if (data.equals("off")) {
digitalWrite(D1, HIGH);
} else {
digitalWrite(D1, LOW);
}
} else if (path.equals("/light/value")) {
if (data.equals("off")) {
digitalWrite(D2, HIGH);
} else {
digitalWrite(D2, LOW);
}
}
}
}
}
Troubleshooting ESP8266 not connecting to WiFi
Failure to connect to the WiFi network can be caused by some factors. Among them I highlight:
1 - The ESP8266 has a particularity of the initial state of its GPIOs during an initialization. As the intention is to make a connection to the Internet, I suggest that you leave the ESP8266 only with the power and communication connections. If you have a NodeMCU you can use only the USB cable.
2 - Wrong filling in of the access data of the router will cause an error in the connection. Please note that you have to put in your code the WLAN SSID and WLAN PASS information, which are, respectively, the name and password of your network. It is worth remembering that the capture of these characters is case sensitive.
3 - If your router is not connected to the Internet, then you will have feedback via the serial monitor of your local IP, but you will not have confirmation of access with the Google server. Test it with your smartphone or computer and check if everything is fine with your Internet connection.
4 - It is difficult, but I have already seen incompatibility with the internet provider. To solve, test on different networks. I suggest that we carry out tests with your smartphone functioning as a WiFi router. You can even check the connected devices quickly and easily.
You can learn more about it in this link (Eduardo Castro) in Brazilian Portuguese:
https://www.filipeflop.com/blog/como-conectar-o-esp8266-a-internet/

IOS boost asio connect from ipv6 network

I am trying to connect a dvr using boost asio library in ios. The application works fine in emulator with in ipv4 network. But when I submit the application on Appstore apple rejected the application as it's not work on ipv6 network. And I can see in the apple site that application should support ipv6 network. https://developer.apple.com/news/?id=05042016a
So I think the problem comes at the section where I am trying to connect to DVR using boost library, where the ip address of the DVR is pulled from DB(hard-coded) and below is the relevant part of the code.
boost::asio::io_service io_service_;
tcp::resolver::iterator endpoint_iter_;
tcp::resolver resolver_; //to healp resolving hostname and ip
stringstream strstream;//create a stringstream
strstream << port;//add number to the stream
endpoint_iter_ = resolver_.resolve(tcp::resolver::query(ip.c_str(),strstream.str()));
start_connect(endpoint_iter_);
// Start the deadline actor. You will note that we're not setting any
// particular deadline here. Instead, the connect and input actors will
// update the deadline prior to each asynchronous operation.
deadline_timer_.async_wait(boost::bind(&dvr_obj::check_deadline, this));
//starting thread for dvr connection
io_service_.reset();
thread_ = new boost::thread(boost::bind(&boost::asio::io_service::run, &io_service_));
start_connect method
void start_connect(tcp::resolver::iterator endpoint_iter)
{
try
{
if (endpoint_iter != tcp::resolver::iterator())
{
drill_debug_info("trying to connect %s \n",name.c_str());
// Set a deadline for the connect operation.
deadline_timer_.expires_from_now(boost::posix_time::seconds(10));
// Start the asynchronous connect operation.
socket_.async_connect(endpoint_iter->endpoint(),
boost::bind(&dvr_obj::handle_connect,
this, _1, endpoint_iter));
}
else
{
// There are no more endpoints to try. Shut down the client.
connectivity = false;
}
} catch (int e) {
connectivity = false;
}
}
So I am confused how to change above code to work on IPV6 network. Could not find any solution in Internet.
You can iterate through the endpoints to find an IPv6 endpoint using the code below:
endpoint_iter_ = resolver_.resolve(tcp::resolver::query(ip.c_str(),strstream.str()));
while (endpoint_iter_ != tcp::resolver::iterator())
{
if (endpoint_iter_->endpoint().protocol() == tcp::v6())
break;
++endpoint_iter_;
}
if (endpoint_iter_ != tcp::resolver::iterator())
{
start_connect(endpoint_iter_);
...
}
else
std::cerr << "IPv6 host not found" << std::endl;

How to connect with SIP server for VoIP call in iOS?

I would like to connect with SIP server for SIP handshake. Could any one help me on how to implement the same in iOS. How should we do it. Should it be done through TCP protocol or can it be done through NSURLSession?
It would be really help full to provide some guidance on the same.
How do we post request or pass parameter to SIP server?
Is it through header or XML?
Any help on this?
I shall recommend building you app on top an SIP SDK that can be found on the net. Prefer to use the TCP as the transport protocol for the SIP Signaling message because - Apple like Connection oriented protocols. As you start getting deeper it should help you better to understand why it makes sense.
NSURLSession is mechanisms to perform URL requests. The SIP signaling is a Protocol packet containing session creation and maintenance information. So i haven't seen any particular use for this for SIP.
As Rajesh mentionned in his answer, TCP (or TLS) is mandatory on iOS to allow receiving data in background: your app will be suspended when it goes to background, but the system will keep an eye on the TCP connection and wake up your app when something happen on the socket to let you handle the event (usually, an incoming call):
In order to ask the system to wake up your app, you have to configure the socket for such VoIP usage:
With C code, you can do this:
//include required
#include <CoreFoundation/CFStream.h>
#include <CFNetwork/CFSocketStream.h>
//additionnal declaration
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
//TODO: open your socket as usual
...
//Configure the socket
CFStreamCreatePairWithSocket (kCFAllocatorDefault, socket, &readStream, &writeStream);
if (readStream != NULL)
CFReadStreamSetProperty (readStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
if (writeStream != NULL)
CFWriteStreamSetProperty (writeStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
if (CFReadStreamOpen (readStream)) {
//CFReadStreamOpen Succeeded
}
if (CFWriteStreamOpen (writeStream)) {
//CFWriteStreamOpen Succeeded
}
//Now, if you go to background, your app will be woken up
...
//When you close the socket
if (readStream != NULL) {
CFReadStreamClose (readStream);
CFRelease (readStream);
}
if (writeStream != NULL) {
CFWriteStreamClose (writeStream);
CFRelease (writeStream);
}
NOTE: Your app must of course be a "Voice Over IP" app (Background Modes settings)

Resources