I'm trying to make a code that can subscribe and publish operations simultaneously. I have this code below that I think should perform the functions simultaneously but it doesn't seem to be working:
#include <Adafruit_MQTT.h>
#include <Adafruit_MQTT_Client.h>
#include <Adafruit_MQTT_FONA.h>
//#include <stackThunk.h>
#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#include "DHT.h"
#define DHTPIN 13
#define DHTTYPE DHT11
#define Relay1 4
#define Relay2 0
#define Relay3 2
#define Relay4 14
//#define WLAN_SSID "((DREAMNET03132490047))" // Your SSID
//#define WLAN_PASS "multan69"
DHT dht(DHTPIN, DHTTYPE);
char str_hum[16];
char str_temp[16];
#define WLAN_SSID "Connect(ow)03002618017" // Your SSID
#define WLAN_PASS "XXXXXXX" // Your password
/************************* Adafruit.io Setup *********************************/
#define AIO_SERVER "io.adafruit.com"
#define AIO_SERVERPORT 1883 // use 8883 for SSL
#define AIO_USERNAME "XXXXXXXXXXXXXX" // Replace it with your username
#define AIO_KEY "XXXXXXXXXXXXXXXXXXXXXXXXXXX" // Replace with your Project Auth Key
/************ Global State (you don't need to change this!) ******************/
// Create an ESP8266 WiFiClient class to connect to the MQTT server.
WiFiClient client;
// or... use WiFiFlientSecure for SSL
//WiFiClientSecure client;
// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
/****************************** Feeds ***************************************/
// Setup a feed called 'onoff' for subscribing to changes.
Adafruit_MQTT_Subscribe Light1 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME"/feeds/Relay1"); // FeedName
Adafruit_MQTT_Subscribe Light2 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/Relay2");
Adafruit_MQTT_Subscribe Light3 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/Relay3");
Adafruit_MQTT_Subscribe Light4 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/Relay4");
Adafruit_MQTT_Publish temp = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/Temperature");
Adafruit_MQTT_Publish hum = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/Humidity");
void MQTT_connect();
void setup() {
Serial.begin(115200);
delay(10);
dht.begin();
pinMode(Relay1, OUTPUT);
pinMode(Relay2, OUTPUT);
pinMode(Relay3, OUTPUT);
pinMode(Relay4, OUTPUT);
// Connect to WiFi access point.
Serial.println(); Serial.println();
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);
WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
// Setup MQTT subscription for onoff feed.
mqtt.subscribe(&Light1);
mqtt.subscribe(&Light3);
mqtt.subscribe(&Light2);
mqtt.subscribe(&Light4);
}
void loop() {
MQTT_connect();
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t");
Serial.print("Heat index: ");
Serial.print(hic);
Serial.print(" *C ");
Serial.print(hif);
Serial.println(" *F");
Serial.print("Temperature in Celsius:");
Serial.println(String(t).c_str());
Serial.print("Temperature in Fahrenheit:");
Serial.println(String(f).c_str());
Serial.print("Humidity:");
Serial.println(String(h).c_str());
//dtostrf(gps_latitude, 4, 2, str_temp);
//dtostrf(gps_longitude, 4, 2, str_hum);
// Now we can publish stuff!
Serial.print(F("\nSending Humidity value: "));
Serial.print(String(h).c_str());
Serial.print("...");
if (! hum.publish(String(h).c_str())) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
}
delay(1000);
Serial.print(F("\nSending Temperature value: "));
Serial.print(String(t).c_str());
Serial.print("...");
if (! temp.publish(String(t).c_str())) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
}
//temperature_work();
Adafruit_MQTT_Subscribe *subscription;
while ((subscription = mqtt.readSubscription(20000))) {
if (subscription == &Light1) {
Serial.print(F("Got: "));
Serial.println((char *)Light1.lastread);
int Light1_State = atoi((char *)Light1.lastread);
digitalWrite(Relay1, Light1_State);
}
if (subscription == &Light2) {
Serial.print(F("Got: "));
Serial.println((char *)Light2.lastread);
int Light2_State = atoi((char *)Light2.lastread);
digitalWrite(Relay2, Light2_State);
}
if (subscription == &Light3) {
Serial.print(F("Got: "));
Serial.println((char *)Light3.lastread);
int Light3_State = atoi((char *)Light3.lastread);
digitalWrite(Relay3, Light3_State);
}
if (subscription == &Light4) {
Serial.print(F("Got: "));
Serial.println((char *)Light4.lastread);
int Light4_State = atoi((char *)Light4.lastread);
digitalWrite(Relay4, Light4_State);
}
}
}
void MQTT_connect() {
int8_t ret;
// Stop if already connected.
if (mqtt.connected()) {
return;
}
Serial.print("Connecting to MQTT... ");
uint8_t retries = 3;
while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000); // wait 5 seconds
retries--;
if (retries == 0) {
// basically die and wait for WDT to reset me
while (1);
}
}
Serial.println("MQTT Connected!");
}
void temperature_work(){
delay(2000);
}
However, when I upload the code of publish and subscription separately, it works fine. Can anyone please take a look at my code attempt and tell me what I'm doing wrong?
Related
I am trying to monitor the temperature with dht22 and esp32 and send the data to the thingsboard. The Arduino sketch is as below:
\
#include "DHT.h"
#include <WiFi.h>
#include <ThingsBoard.h>
#define WIFI_SSID "*****"
#define WIFI_PASSWORD "******"
#define TOKEN "DHT22_TEMP"
// DHT
#define DHTPIN 2
#define DHTTYPE DHT22
char thingsboardServer[] = "demo.thingsboard.io";
WiFiClient wifiClient;
// Initialize DHT sensor.
DHT dht(DHTPIN, DHTTYPE);
ThingsBoard tb(wifiClient);
int status = WL_IDLE_STATUS;
unsigned long lastSend;
void setup()
{
Serial.begin(115200);
dht.begin();
delay(10);
InitWiFi();
lastSend = 0;
}
void loop()
{
if ( !tb.connected() ) {
reconnect();
}
if ( millis() - lastSend > 1000 ) { // Update and send only after 1 seconds
getAndSendTemperatureAndHumidityData();
lastSend = millis();
}
tb.loop();
}
void getAndSendTemperatureAndHumidityData()
{
Serial.println("Collecting temperature data.");
// Reading temperature or humidity takes about 250 milliseconds!
float humidity = dht.readHumidity();
// Read temperature as Celsius (the default)
float temperature = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.println("Sending data to ThingsBoard:");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" *C ");
tb.sendTelemetryFloat("temperature", temperature);
tb.sendTelemetryFloat("humidity", humidity);
}
void InitWiFi()
{
Serial.println("Connecting to AP ...");
// attempt to connect to WiFi network
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to AP");
}
void reconnect() {
// Loop until we're reconnected
while (!tb.connected()) {
status = WiFi.status();
if ( status != WL_CONNECTED) {
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to AP");
}
Serial.print("Connecting to ThingsBoard node ...");
if ( tb.connect(thingsboardServer, TOKEN) ) {
Serial.println( "[DONE]" );
} else {
Serial.print( "[FAILED]" );
Serial.println( " : retrying in 5 seconds]" );
// Wait 5 seconds before retrying
delay( 5000 );
}
}
}
When this code is uploaded, it says:
"Connecting to ThingsBoard Server... [TB] Connection to server failed
[Failed] Retrying in 5 seconds"
I expect it to connect to thingsboard and send the data to it, Thingsboard is installed on-premise.
i never use thingsboar demo, i was using thingsboard cloud, to set up connection the server i use it like a define
#define TOKEN "YOUR_ACCESS_TOKEN"
#define THINGSBOARD_SERVER "demo.thingsboard.io"
all the rest must work, i will see again the example code from thingsboard example
I have some code I have been putting on an ESP8266-12e board. Until recently it always worked fine. Now though when I finish uploading the code the blue light on the ESP8266-12e is staying on. I have tried it on two different board and the blue light stay on on both. I can't figure out what I changed in the code.
I have decided to put it up and have everyone look at it and let me know what I may be missing.
I hope someone can find something.
My code:
//NodeMCU 1.0 (ESP-12E Module constant connect)
#include <ESP8266WiFi.h>
#include <FS.h> //https://github.com/esp8266/Arduino
#include <EEPROM.h>
//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
//MQTT stuff
#define AIO_SERVER "go,here"
#define AIO_SERVERPORT SSSS // 8883 for MQTTS
#define AIO_USERNAME "FFFFFF"
#define AIO_KEY "XXXXXXXXXXXXXXXXXXXXXXX"
int tripper = 1;
#define MQTT_CONN_KEEPALIVE 18000000
#define LED3 16
//NEW AUTOCONNECT
const byte numChars = 32;
char receivedChars[numChars];
char Password[36]="";
char apiKey[16]="";
char apiKey2[32]="";
char channelKey[16];
char channelKey2[16];
String channelKey21= "&";
byte pinState = LOW;
char ssid[] = "";
char pass[] = "";
String Label = "";
String TOTAL = "";
uint32_t m=0;
WiFiClient client;
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
// Setup a feed called 'onoff' for subscribing to changes.
Adafruit_MQTT_Subscribe trip2 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/trip");
Adafruit_MQTT_Publish move1 = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/motion");
/*************************** Error Reporting *********************************/
Adafruit_MQTT_Subscribe errors = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/errors");
Adafruit_MQTT_Subscribe throttle = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/throttle");
//NEW AUTOCONNECT
int LED2 = 13;
int MOVEMENT = 5;
//send ssid/pass
String f;
//mqtt
char temperature[]="000";
String level;
String battery;
String trip;
String date;
int addr = 0;
//END NEW AUTOCONNECT
void MQTT_connect();
void setup() {
Serial.begin(115200);
pinMode(MOVEMENT,OUTPUT);
digitalWrite(MOVEMENT,LOW);
pinMode(D5,OUTPUT);
digitalWrite(D5,LOW);
pinMode(LED3,OUTPUT);
digitalWrite(LED3,LOW);
pinMode(LED2,INPUT);
Serial.println(F("Adafruit MQTT demo"));
//NEW AUTOCONNECT
WiFiManager wifiManager;
// put your setup code here, to run once:
WiFiManagerParameter customAPIKey("apiKey", "Time Zone #", apiKey, 16);
wifiManager.addParameter(&customAPIKey);
wifiManager.autoConnect("FloWT2");
Serial.println("Connected");
strcpy(apiKey,customAPIKey.getValue());
EEPROM.begin(512); //Initialize EEPROM
EEPROM.write(addr, 'A'); //Write character A
addr++; //Increment address
EEPROM.write(addr, 'B'); //Write character A
String www = apiKey;
Serial.print("www");
Serial.print (www);
for(int i=0;i<www.length();i++) //loop upto string lenght www.length() returns length of string
{
EEPROM.write(0x0F+i,www[i]); //Write one by one with starting address of 0x0F
}
EEPROM.commit();
delay (2000);
if (WiFi.status() == WL_DISCONNECTED) {
wifiManager.autoConnect("FloWT2");
delay(60000);}
if (WiFi.status() == WL_CONNECTED) { Serial.println("Connected");
delay(1000);
//get time zone
EEPROM.begin(512);
Serial.println(""); //Goto next line, as ESP sends some garbage when you reset it
Serial.print(char(EEPROM.read(addr))); //Read from address 0x00
addr++; //Increment address
Serial.print(char(EEPROM.read(addr))); //Read from address 0x01
addr++; //Increment address
Serial.println(char(EEPROM.read(addr))); //Read from address 0x02
//Read string from eeprom
String www;
//Here we dont know how many bytes to read it is better practice to use some terminating character
//Lets do it manually www.circuits4you.com total length is 20 characters
for(int i=0;i<16;i++)
{
www = www + char(EEPROM.read(0x0F+i)); //Read one by one with starting address of 0x0F
}
Serial.println("this");
Serial.print(www);
Serial.println("IP address: "); Serial.println(WiFi.localIP());
// Setup MQTT subscription for onoff feed
mqtt.subscribe(&trip2);
// Setup MQTT subscriptions for throttle & error messages
mqtt.subscribe(&throttle);
mqtt.subscribe(&errors);
WiFiClient client;
delay(2000);
Serial.printf("SSID: %s\n", WiFi.SSID().c_str());
Serial.printf("SSID: %s\n", WiFi.psk().c_str());
String ssidString = WiFi.SSID().c_str();
String pskString = WiFi.psk().c_str();
f = String('<')+String("Hi")+String(',')+String(ssidString)+String(',')+String(pskString)+String(',')+String(www)+String('>');
delay (1000);
Serial.print(f);
delay(500);
Serial.print(f);
delay(500);
Serial.print(f);
delay(500);
Serial.print(f);
delay(500);
Serial.print(f);
delay(500);
}
client.stop();
}
void loop() {
MQTT_connect();
uint32_t m=0;
Serial.print(F("\nSending motion val "));
Serial.print(m);
Serial.print("...");
if (! move1.publish(m)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
}
long state = digitalRead(LED2);
if(state == HIGH) {
m = 1;
Serial.print(F("\nSending motion val "));
Serial.print(m);
Serial.print("...");
digitalWrite(MOVEMENT,HIGH);
delay(1000);
digitalWrite(MOVEMENT,LOW);
if (! move1.publish(m)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
}
}
else{
}
// this is our 'wait for incoming subscription packets' busy subloop
// try to spend your time here
//12e
Adafruit_MQTT_Subscribe *subscription;
while ((subscription = mqtt.readSubscription(5000))) {
if (subscription == &trip2) {
Serial.print(F("Got onoff: "));
Serial.println((char *)trip2.lastread);
uint16_t sliderval = atoi((char *)trip2.lastread);
//THIS IS FOR LATCHING RELAY TURN ON D5 HIGH THEN OFF AFTER 1 SECOND
//NEXt TURN D6 HIGH THEN OFF AFTER A SECONDS
if((sliderval ==0)&&(tripper == 1)){
digitalWrite(D5,HIGH);
delay(1000);
digitalWrite(D5,LOW);
tripper = 2;
Serial.print(tripper);
Serial.print("tripped");
}
else if(sliderval == 50){
}
else if((sliderval == 100)&&(tripper == 2)){
digitalWrite(LED3,HIGH);
delay(1000);
digitalWrite(LED3,LOW);
tripper = 1;
Serial.print(tripper);
Serial.print("tripped2");
}
} else if(subscription == &errors) {
Serial.print(F("ERROR: "));
Serial.println((char *)errors.lastread);
} else if(subscription == &throttle) {
Serial.println((char *)throttle.lastread);
}
}
}
void MQTT_connect() {
int8_t ret;
// Stop if already connected.
if (mqtt.connected()) {
return;
}
Serial.print("Connecting to MQTT... ");
uint8_t retries = 3;
while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000); // wait 5 seconds
retries--;
if (retries == 0) {
// basically die and wait for WDT to reset me
while (1);
}
}
Serial.println("MQTT Connected!");
}
I hope it is not toooo long.
Anyway I hope someone can find my problem. Everything works ok with the blue light on it is just know supposed to be that I can tell.
When I upload another code it doesn't stay on so it has to be in the code.
I will keep looking.
THANKS
So I got the blue light to go off. Instead of pinMode(D4,INPUT); and digitalWrite(D4,LOW); D4 is pin 16 which is the wake pin. So I had to define it thus #define LED3 16 and then pinMode(LED3,INPUT); and digitalWrite(LED3,LOW); I will change my original code to reflect these changes.
I am making a project on home automation with temperature reading using NodeMCU (ESP8266-12E). I am using a DHT11 sensor with DHT11.h library, but my temperature sensor is showing me "nan" instead of any value. I don't know where I am lagging.
My code is given below:
#include "DHT.h" // including the library of DHT11 temperature and humidity sensor
#define DHTTYPE DHT11 // DHT 11
#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#define Relay1 D1
#define Relay2 D2
#define Relay3 D3
#define Relay4 D4
#define DHTPIN D0
DHT dht(DHTPIN, DHTTYPE);
float temp_f;
String webString = "";
unsigned long previousMillis = 0;
const long interval = 2300;
#define WLAN_SSID "internet" // Your SSID
#define WLAN_PASS "*********" // Your password
/************************* Adafruit.io Setup *********************************/
#define AIO_SERVER "io.adafruit.com" //Adafruit Server
#define AIO_SERVERPORT 1883
#define AIO_USERNAME "foo" // Username
#define AIO_KEY "bar" // Auth Key
//WIFI CLIENT
WiFiClient client;
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
// Setup a feed called 'photocell' for publishing.
// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>
const char TEMP_FEED[] PROGMEM = AIO_USERNAME "/feeds/photocell";
Adafruit_MQTT_Publish photocell = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME"/feeds/photocell");
Adafruit_MQTT_Subscribe Light1 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME"/feeds/Relay1"); // Feeds name should be same everywhere
Adafruit_MQTT_Subscribe Light2 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME"/feeds/Relay2");
Adafruit_MQTT_Subscribe Light3 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME"/feeds/Relay3");
Adafruit_MQTT_Subscribe Light4 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME"/feeds/Relay4");
void MQTT_connect();
void setup()
{
Serial.begin(115200);
delay(10);
dht.begin();
// Print temperature sensor details.
pinMode(Relay1, OUTPUT);
pinMode(Relay2, OUTPUT);
pinMode(Relay3, OUTPUT);
pinMode(Relay4, OUTPUT);
// Connect to WiFi access point.
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);
WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
temp_f = dht.readTemperature(true);
Serial.println();
Serial.print("Initial Temp: ");
Serial.println(temp_f);
Serial.println();
mqtt.subscribe(&Light1);
mqtt.subscribe(&Light3);
mqtt.subscribe(&Light2);
mqtt.subscribe(&Light4);
}
int delayTime = 300000; //Wait 5 minutes before sending data to web
int startDelay = 0;
void loop()
{
MQTT_connect();
if (millis() - startDelay < delayTime) {
Serial.println("waiting delaytime");
}
else {
temp_f = dht.readTemperature(true); //Get temp in Farenheit
startDelay = millis();
Serial.print(F("\nSending temp: "));
Serial.print(temp_f);
Serial.print("...");
if (!photocell.publish(temp_f)) { //Publish to Adafruit
Serial.println(F("Failed"));
}
else {
Serial.println(F("Sent!"));
}
}
/* //int t = dht.readTemperature(true);
// t = t/100000000;
Serial.print(F("\nSending photocell val "));
Serial.print(t);
Serial.print("...");
if (! photocell.publish(t)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
}*/
Adafruit_MQTT_Subscribe* subscription;
while ((subscription = mqtt.readSubscription(2000))) {
if (subscription == &Light1) {
Serial.print(F("Got: "));
Serial.println((char*)Light1.lastread);
int Light1_State = atoi((char*)Light1.lastread);
digitalWrite(Relay1, Light1_State);
}
if (subscription == &Light2) {
Serial.print(F("Got: "));
Serial.println((char*)Light2.lastread);
int Light2_State = atoi((char*)Light2.lastread);
digitalWrite(Relay2, Light2_State);
}
if (subscription == &Light3) {
Serial.print(F("Got: "));
Serial.println((char*)Light3.lastread);
int Light3_State = atoi((char*)Light3.lastread);
digitalWrite(Relay3, Light3_State);
}
if (subscription == &Light4) {
Serial.print(F("Got: "));
Serial.println((char*)Light4.lastread);
int Light4_State = atoi((char*)Light4.lastread);
digitalWrite(Relay4, Light4_State);
}
}
// this is our 'wait for incoming subscription packets and callback em' busy subloop
// try to spend your time here:
mqtt.processPackets(500);
}
void MQTT_connect()
{
int8_t ret;
if (mqtt.connected()) {
return;
}
Serial.print("Connecting to MQTT... ");
uint8_t retries = 3;
while ((ret = mqtt.connect()) != 0) {
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000);
retries--;
if (retries == 0) {
while (1);
}
}
Serial.println("MQTT Connected!");
}
you try to read temperature and humidity in setup(). but you need to wait 2s at minima after the dht.begin and before reading, because Sensor readings may also be up to 2 seconds
so add delay(2000) before the first reading..
I have arduino uno + wifishield and if fails to connect to Bluemix. It gives this error:
"Closed connection from 194.228.11.222. The operation is not authorized."
Any idea why the connection gets kicked out? What operation is not authorized?
Thanks for any idea ;)
======
Here is the code:
#include <SPI.h>
#include <Ethernet.h>
#include <WiFi.h>
#include <WifiIPStack.h>
#include <IPStack.h>
#include <Countdown.h>
#include <MQTTClient.h>
#define MQTT_MAX_PACKET_SIZE 100
#define SIZE 100
#define MQTT_PORT 1883
#define PUBLISH_TOPIC "iot-2/evt/status/fmt/json"
#define SUBSCRIBE_TOPIC "iot-2/cmd/+/fmt/json"
#define USERID "use-token-auth"
#define CLIENT_ID "d:6735ra:hlinoponie:petasek"
#define MS_PROXY "6735ra.messaging.internetofthings.ibmcloud.com"
#define AUTHTOKEN “xxxxx”
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0xD6, 0x8F };
WiFiClient c;
IPStack ipstack(c);
MQTT::Client<IPStack, Countdown, 100, 1> client = MQTT::Client<IPStack, Countdown, 100, 1>(ipstack);
String deviceEvent;
char ssid[] = “XXXXX”; // your network SSID (name)
char pass[] = “XXXXX”; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
void setup() {
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while (true);
}
String fv = WiFi.firmwareVersion();
if ( fv != "1.1.0" )
Serial.println("Please upgrade the firmware");
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
// wait 5 seconds for connection:
delay(5000);
}
// you're connected now, so print out the data:
Serial.print("Hooray!!! You're connected to the network\n");
}
void loop() {
float tep = mojeDHT.readTemperature();
float vlh = mojeDHT.readHumidity();
int rc = -1;
if (!client.isConnected()) {
Serial.println("Connecting to Watson IoT Foundation ...");
rc = ipstack.connect((char*)MS_PROXY, MQTT_PORT);
MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
data.MQTTVersion = 3;
data.clientID.cstring = (char*)CLIENT_ID;
data.username.cstring = (char*)USERID;
data.password.cstring = (char*)AUTHTOKEN;
data.keepAliveInterval = 60;
rc = -1;
while ((rc = client.connect(data)) != 0) {
Serial.println("rc=");
Serial.println(rc);
delay(2000);
}
Serial.println("Connected successfully\n");
// Serial.println("Temperature(in C)\tDevice Event (JSON)");
Serial.println("____________________________________________________________________________");
}
Serial.println("\n");
MQTT::Message message;
message.qos = MQTT::QOS0;
message.retained = false;
deviceEvent = String("{\"d\":{\"myName\":\"Arduino Uno\",\"temperature\":");
char buffer[60];
// convert double to string
dtostrf(getTemp(),1,2, buffer);
deviceEvent += buffer;
deviceEvent += "}}";
Serial.print("\t");
Serial.print(buffer);
Serial.print("\t\t");
deviceEvent.toCharArray(buffer, 60);
Serial.println(buffer);
message.payload = buffer;
message.payloadlen = strlen(buffer);
rc = client.publish(PUBLISH_TOPIC, message);
if (rc != 0) {
Serial.print("return code from publish was ");
Serial.println(rc);
}
client.yield(5000);
}
/*
This function is reproduced as is from Arduino site => http://playground.arduino.cc/Main/InternalTemperatureSensor
*/
double getTemp(void) {
unsigned int wADC;
double t;
ADMUX = (_BV(REFS1) | _BV(REFS0) | _BV(MUX3));
ADCSRA |= _BV(ADEN); // enable the ADC
delay(20); // wait for voltages to become stable.
ADCSRA |= _BV(ADSC); // Start the ADC
// Detect end-of-conversion
while (bit_is_set(ADCSRA,ADSC));
// Reading register "ADCW" takes care of how to read ADCL and ADCH.
wADC = ADCW;
// The offset of 324.31 could be wrong. It is just an indication.
t = (wADC - 324.31 ) / 1.22;
// The returned temperature is in degrees Celcius.
return (t);
}
It might be the case your organizations is configured to block non-secure connections (since you are using port 1883). Check the step 5 on this recipe
https://developer.ibm.com/recipes/tutorials/connect-an-arduino-uno-device-to-the-ibm-internet-of-things-foundation/
I noticed this error in the log: The topic is not valid: Topic="lwt" ClientID="d:6735ra:hlinoponie:petasek" Reason="The topic does not match an allowed rule".
I didn't see that topic listed in your code, but you may want to check to see how that may be getting set as topic.
I have a simple code in which I am trying to connect to HiveMQ open broker and subscribe to a topic to listen to incoming messages.
here is the code
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char *ssid = "P9Inct"; // cannot be longer than 32 characters!
const char *pass = "P9inct123*"; //
const char *mqtt_server = "broker.hivemq.com";
const int mqtt_port = 1883;
const char *mqtt_user = "testUser";
const char *mqtt_pass = "abc123";
const char *mqtt_client_name = "12312312332212";
#define BUFFER_SIZE 100
String incoming="";
String did="";
String state="";
// Update these with values suitable for your network.
//IPAddress server(172, 16, 0, 2);
String DEVID="8581870006";//"6931108641";//old
WiFiClient wclient;
PubSubClient client(wclient, mqtt_server,mqtt_port);
void callback(const MQTT::Publish& pub) {
// handle message arrived
Serial.print(pub.topic());
Serial.print(" => ");
if (pub.has_stream()) {
uint8_t buf[BUFFER_SIZE];
int read;
while (read = pub.payload_stream()->read(buf, BUFFER_SIZE)) {
Serial.write(buf, read);
}
pub.payload_stream()->stop();
Serial.println("");
} else
Serial.println(pub.payload_string());
////////////////////////////////////////////
incoming=String(pub.payload_string());
Serial.println(pub.payload_string());
Serial.println(incoming);
}
void setup() {
// Setup console
Serial.begin(115200);
delay(10);
Serial.println();
Serial.println();
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
Serial.print("Connecting to ");
Serial.print(ssid);
Serial.println("...");
WiFi.begin(ssid, pass);
if (WiFi.waitForConnectResult() != WL_CONNECTED)
return;
Serial.println("WiFi connected");
}
if (WiFi.status() == WL_CONNECTED) {
if (!client.connected()) {
Serial.println("Connecting to MQTT server");
if (client.connect(MQTT::Connect(mqtt_client_name)
.set_auth(mqtt_user, mqtt_pass))) {
Serial.println("Connected to MQTT server");
client.set_callback(callback);
client.subscribe("diy/1"+DEVID);
} else {
Serial.println("Could not connect to MQTT server");
}
}
if (client.connected())
client.loop();
}
}
WiFi connection is working fine but, communication via broker is not working and it always gives the message "Could not connect to MQTT server". How to make esp8266 work with HiveMQ broker. The dashboard of borker is
http://www.mqtt-dashboard.com/
So, you are connected. You have unnecessary print line in your loop. Try to adapt on this :
/* Incoming data callback. */
void callback(char* topic, byte* payload, unsigned int length)
{
char payloadStr[length + 1];
memset(payloadStr, 0, length + 1);
strncpy(payloadStr, (char*)payload, length);
Serial.printf("Topic : [%s]\n", topic);
Serial.printf("Payload : %s\n", payloadStr);
}
void performConnect()
{
uint16_t connectionDelay = 5000;
while (!client.connected())
{
if (client.connect(MQTT_CLIENT_ID, MQTT_USERNAME, MQTT_KEY))
{
Serial.printf("Connected to Broker.\n");
client.subscribe("diy/1"+DEVID);
}
else
{
Serial.printf("MQTT Connect failed, rc = %d\n", client.state());
Serial.printf("Trying again in %d msec.\n", connectionDelay);
delay(connectionDelay);
}
}
}
void loop()
{
if (!client.connected())
{
performConnect();
}
client.loop();
}