Failed to connect to Thingsboard Server - iot

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

Related

Publish/Subscribe simultaneously using MQTT

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?

Is it possible to send a coordinate data to firebase realtime database that has more than 2 decimal places?

i am using NodeMCU and sim808 microcontroller and i am sending the data that i received from my sim808 to my firebase realtime database using firebase-arduino library, and i noticed that the data i recieved in my firebase data base is only a 2 decimal place float which is not that accurate considering the data that i am sending are coordinates
below is the code that i am using:
#include <DFRobot_sim808.h>
#include <SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>
#define PIN_TX 5
#define PIN_RX 4
// Set these to run example.
#define FIREBASE_HOST "..........com"
#define FIREBASE_AUTH "............."
#define WIFI_SSID "........."
#define WIFI_PASSWORD ".......!"
SoftwareSerial mySerial(PIN_TX,PIN_RX);
DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,
void setup() {
Serial.begin(9600);
mySerial.begin(9600);
while(!sim808.init()) {
delay(1000);
Serial.print("Sim808 init error\r\n");
}
//************* Turn on the GPS power************
if( sim808.attachGPS())
{
Serial.println("Open the GPS power success");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println();
Serial.print("connected: ");
Serial.println(WiFi.localIP());
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
}
else {
Serial.println("Open the GPS power failure");
}
}
void loop() {
while (sim808.getGPS()){
Serial.print("Latgps: ");
Serial.println(sim808.GPSdata.lat);
Serial.print("Longps: ");
Serial.println(sim808.GPSdata.lon);
// set value
Firebase.set("latitude",sim808.GPSdata.lat);
// handle error
if (Firebase.failed()) {
Serial.print("setting /gps failed:");
Serial.println(Firebase.error());
return;
}
delay(1000);
// update value
Firebase.set("longitude", sim808.GPSdata.lon);
// handle error
if (Firebase.failed()) {
Serial.print("setting /gps failed:");
Serial.println(Firebase.error());
return;
}
delay(1000);
// get value
Serial.print("latfire: ");
Serial.println(Firebase.getFloat("latitude" ), 4);
Serial.print("lonfire: ");
Serial.println(Firebase.getFloat("longitude"), 4);
delay(1000);
// remove value
// set string value
Firebase.setString("message", "........");
// handle error
if (Firebase.failed()) {
Serial.print("setting /message failed:");
Serial.println(Firebase.error());
return;
}
delay(1000);
// set bool value
// append a new value to /logs
}
}

I am writing a code to read DHT11 value and control 4 relay but temp. sensor is showing me "nan" everytime

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..

Arduino ESP8266 01 MQTT Raspberry pi

I want to use ESP 8266 01 and arduino uno as client in MQTT. The code For ESP8266 01 is successfully compiled and I'M getting errors in Arduino uno
The error is 'messageTemp' was not declared in this scope
Amd also I have a thought of using stm32xx in client.
If I compile for that
exit status 1
ISO C++ forbids comparison between pointer and integer [-fpermissive]
above is the error I'm getting
1)ESP code
// Loading the ESP8266WiFi library and the PubSubClient library
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Change the credentials below, so your ESP8266 connects to your router
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
const char* mqtt_server = "YOUR_RPi_IP_Address";
// Initializes the espClient
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("WiFi connected - ESP IP address: ");
Serial.println(WiFi.localIP());
}
if(topic=="home/office/esp1/gpio2"){
Serial.print("Changing GPIO 2 to ");
if(messageTemp == "1"){
// digitalWrite(ledGPIO2, HIGH);
Serial.print("On");
}
else if(messageTemp == "0"){
// digitalWrite(ledGPIO2, LOW);
Serial.print("Off");
}
}
Serial.println();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
client.subscribe("home/office/esp1/gpio2");
}
else
{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
Code for Arduino UNO
void setup(){
Serial.begin(9600);
pinMode(12, OUTPUT);
digitalWrite(12, HIGH);
String messageTemp;
}
void callback(String topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();
}
void loop ()
{
if (Serial.available()){
char topic = Serial.read();
{
if (topic=="home/office/esp1/gpio2")
{
Serial.print("Changing GPIO 2 to ");
if(messageTemp == "1"){
digitalWrite(12, HIGH);
Serial.print("On");
}
else if(messageTemp == "0")
{
digitalWrite(12, LOW);
Serial.print("Off");
}
}}}}
ESP code doesn't look the whole source code you provided. In case of Arduino UNO, if you're intending to use messageTemp as a global variable, then you need to declare it only one time outside of functions. In the above code, you declared it twice in setup() and callback(), then those are considered as local variables. Even in loop(), there's no declaration, this should create the compile error.

arduino uno + wifishield cannot connect bluemix using token

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.

Resources