Hello all,
first thing i have very VERY little knowledge about programming.
I am able to analyse codes and from there add things to example sketches.
I have a example sketch , i made some changes to it. It is now connecting to WiFi and a MQTT broker.
I also added the sketch so that i get a unique clientID. But the esp-12 keeps losing the connection with the MQTT broker. I found this to make the sketch reconnect to the MQTT broker after 5 seconds.
When i restart my mosquitto i see in openhab2 that my CO2 sensor is posting data. so it look like it is working. But on a reconnect the sketch need to post to a topic "SCD3-/Info" a message "Reconnected"
I have mqtt.fx as a MQTT client. But i dont see the message( i am not sure that mqtt.fx auto reconnects so it could be that the message is posted but that mqtt.fx has no connection with mosquitto and there for is not showing the Info message)
Can someone please check my code and tell me if i made the reconnect part in a correct way. So that when i lose the MQTT connection it will try to reconnect after 5 seconds.
This is the added sketch i have:
#include <Wire.h>
#include "paulvha_SCD30.h"
#include "SparkFunBME280.h"
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
//Wifi Settings
const char* ssid = "MySSID";
const char* password = "Mypass";
//MQTT Settings
const char* mqttServer = "192.168.178.192";
const int mqttPort = 1883;
const char* mqttUser = "openhab";
const char* mqttPassword = "Mypass";
WiFiClient espClient;
PubSubClient client(espClient);
long lastReconnectAttempt = 0;
boolean reconnect() {
if (client.connect("clientId", mqttUser, mqttPassword )) {
// Once connected, publish an announcement...
client.publish("SCD30/Info","Reconnected");
}
return client.connected();
}
//////////////////////////////////////////////////////////////////////////
// set SCD30 driver debug level (ONLY NEEDED CASE OF SCD30 ERRORS) //
// //
// 0 : no messages //
// 1 : request sending and receiving //
// 2 : request sending and receiving + show protocol errors //
//////////////////////////////////////////////////////////////////////////
#define scd_debug 0
//////////////////////////////////////////////////////////////////////////
//////////////// NO CHANGES BEYOND THIS POINT NEEDED /////////////////////
//////////////////////////////////////////////////////////////////////////
BME280 mySensor; //Global sensor object
SCD30 airSensor;
// hold statistics
float temp_tot = 0;
float temp_cnt = 0;
float hum_tot = 0;
float hum_cnt = 0;
float temp_max = 0;
float hum_max = 0;
// status
int detect_BME280 = 0;
void setup()
{
char buf[10];
Serial.begin(115200);
Serial.println("\nSCD30 + BME280 Example);");
WiFi.begin(ssid, password);
IPAddress ip(192,168,178,200);
IPAddress gateway(192,168,178,1);
IPAddress subnet(255,255,255,0);
WiFi.config(ip, gateway, subnet);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
client.setServer(mqttServer, mqttPort);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
if (client.connect("clientId", mqttUser, mqttPassword )) {
Serial.println("connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
lastReconnectAttempt = 0;
}
}
Wire.begin();
// set driver debug level
// 0 : no messages
// 1 : request sending and receiving
// 2 : request sending and receiving + show protocol errors
airSensor.setDebug(scd_debug);
if (mySensor.beginI2C() == false) // Begin communication over I2C
{
Serial.println("The BME280 did not respond. Please check wiring.");
}
else
{
detect_BME280 = 1;
}
// This will cause readings to occur every two seconds and automatic calibration
// on an ESP8266 must called last to set the clock stretching correct for SCD30
airSensor.begin(Wire);
//This will cause SCD30 readings to occur every two seconds
if (airSensor.begin() == false)
{
Serial.println("The SCD30 did not respond. Please check wiring.");
while(1);
}
// Read SCD30 serial number as printed on the device
// buffer MUST be at least 7 digits (6 serial + 0x0)
airSensor.getSerialNumber(buf);
Serial.print("serial number: ");
Serial.println(buf);
}
void loop()
{
float co2,temps,hums, tempb, humb, pressure;
if (!client.connected()) {
long now = millis();
if (now - lastReconnectAttempt > 5000) {
lastReconnectAttempt = now;
// Attempt to reconnect
if (reconnect()) {
lastReconnectAttempt = 0;
}
}
} else {
// Client connected
client.loop();
}
if (airSensor.dataAvailable())
{
//serialTrigger(); // option to wait for user enter instead of constant loop
Serial.print(F("SCD30 : co2(ppm) : "));
Serial.print(airSensor.getCO2());
co2 = airSensor.getCO2();
client.publish("SCD30/co2", String(co2, 0).c_str());
Serial.print(F("\ttemp(C): "));
temps = airSensor.getTemperature();
Serial.print(temps, 2);
client.publish("SCD30/temperature", String(temps).c_str());
Serial.print(F("\thumidity(%): "));
hums = airSensor.getHumidity();
Serial.print(hums, 1);
client.publish("SCD30/humidity", String(hums).c_str());
Serial.println();
// if BME280 was detected include the information & statistics
if (detect_BME280 == 1)
{
Serial.print(F("BME280: Pressure: "));
pressure = mySensor.readFloatPressure()/100;
Serial.print(pressure, 0);
Serial.print(F("\ttemp(C): "));
tempb = mySensor.readTempC();
//tempb = mySensor.readTempF();
Serial.print(tempb, 2);
Serial.print(F("\thumidity(%): "));
humb =mySensor.readFloatHumidity();
Serial.print(humb, 1);
Serial.print(F("\tAlt(m): "));
Serial.print(mySensor.readFloatAltitudeMeters(), 1);
//Serial.print(mySensor.readFloatAltitudeFeet(), 1);
Serial.println();
// count TOTAL delta
temp_tot += temps - tempb;
hum_tot += hums - humb;
// count samples
temp_cnt++;
hum_cnt++;
// obtain maximum delta
if (temps > tempb)
{
if (temp_max < temps - tempb) temp_max = temps - tempb;
}
else
{
if (temp_max < tempb - temps) temp_max - tempb- temps;
}
if (hums > humb)
{
if (hum_max < hums-humb) hum_max = hums - humb;
}
else
{
if (hum_max < humb-hums) hum_max = humb - hums;
}
Serial.print(F("Delta avg temp : "));
Serial.print(temp_tot/temp_cnt, 2);
Serial.print(F(" Delta avg humidity : "));
Serial.print(hum_tot/hum_cnt,2);
Serial.print(F(" Biggest delta temp : "));
Serial.print(temp_max);
Serial.print(F(" Biggest delta humidity : "));
Serial.print(hum_max);
Serial.println("\n");
// Pressure adjustment, current ambient pressure in mBar: 700 to 1200 read from BME80
airSensor.setAmbientPressure(pressure);
}
}
else
Serial.println(F("No SCD30 data"));
// only every 2 seconds is data available
delay(2000);
}
/* serialTrigger prints a message, then waits for something
* to come in from the serial port.
*/
void serialTrigger()
{
Serial.println();
Serial.println(F("press enter"));
Serial.println();
while (!Serial.available());
while (Serial.available())
Serial.read();
}
Greetings