Hello,
i have a problem with the formatting in the setup function.
I am not able to figure it out.
Can someone have a look whats going on and where the error is?
I have tried hours to find i but i think i am blind for my own code at this point..
Error from console says:
WaterFlowSensor_funktioniert_v2_wlan_json:155:1: error: expected unqualified-id before 'else'
155 | else {
| ^~~~
The error refers to this line in the setup funktion:
else {
Serial.println("failed to mount FS");
}
Here is the complete code:
#include <FS.h> //this needs to be first, or it all crashes and burns...
#ifdef ESP32
#include <SPIFFS.h>
#endif
//needed for library
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#include <ArduinoJson.h> //https://github.com/bblanchon/ArduinoJson
#include <DNSServer.h>
#include <PubSubClient.h>
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
char configFileName[] = "/config.json";
#define MQTTSERVER "192.168.1.101" // Home Server
#define MQTTSERVERPORT "1883"
#define MQTTTOPIC "Test"
#define MQTTID "1" // Leave blank to auto generate one
#define MQTTUSER "username"
#define MQTTPASSWORD "password"
char mqtt_server[20] = MQTTSERVER; // Placeholders for MQTT server settings
char mqtt_port[6] = MQTTSERVERPORT;
char mqtt_user[20] = MQTTUSER;
char mqtt_pass[20] = MQTTPASSWORD;
char mqtt_ID[20] = MQTTID;
char mqtt_topic[20] = MQTTTOPIC;
WiFiClient espClient;
PubSubClient client(espClient);
WiFiManager wifiManager;
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
#define SENSOR 14
#define RelaisPin 5
#define resteButton 1 //D6
long currentMillis = 0;
long previousMillis = 0;
int interval = 1000;
boolean ledState = LOW;
float calibrationFactor = 4.5;
volatile byte pulseCount;
byte pulse1Sec = 0;
float flowRate;
unsigned long flowMilliLitres;
unsigned int totalMilliLitres;
float flowLitres;
float totalLitres;
int percentageHumididy;
char relais;
int restebuttonstat = 0;
uint8_t wlan_status;
int count_mqtt_fail = 0;
String topic_string;
String flowRate_out_s;
String FlowLiters_out_s;
String FlowMiliLiters_out_s;
String m_perc_in_s;
String Ralais1_in_S;
const char *flowRate_out;
const char *FlowLiters_out;
const char *FlowMiliLiters_out;
const char *m_perc_in;
const char *Ralais1_in;
//flag for saving data
bool shouldSaveConfig = false;
void IRAM_ATTR pulseCounter()
{
pulseCount++;
}
//callback notifying us of the need to save config
void saveConfigCallback () {
Serial.println("Should save config");
shouldSaveConfig = true;
}
void reset_setting() {
// Reset Wifi settings for testing
wifiManager.resetSettings();
//clean FS for testing
SPIFFS.format();
//ESP.reset();
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
delay(500);
//reset_setting();
//read configuration from FS json
Serial.println("mounting FS...");
if (SPIFFS.begin()) {
Serial.println("mounted file system");
if (SPIFFS.exists(configFileName)) {
//file exists, reading and loading
Serial.println("reading config file");
File configFile = SPIFFS.open(configFileName, "r");
if (configFile) {
Serial.println("opened config file");
size_t size = configFile.size();
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
#ifdef ARDUINOJSON_VERSION_MAJOR >= 6
DynamicJsonDocument json(1024);
auto deserializeError = deserializeJson(json, buf.get());
serializeJson(json, Serial);
if ( ! deserializeError ) {
#else
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.parseObject(buf.get());
json.printTo(Serial);
if (json.success()) {
#endif
Serial.println("\nparsed json");
strcpy(mqtt_server, json["mqtt_server"]);
strcpy(mqtt_port, json["mqtt_port"]);
strcpy(mqtt_topic, json["mqtt_topic"]);
strcpy(mqtt_ID, json["mqtt_ID"]);
strcpy(mqtt_user, json["mqtt_user"]);
strcpy(mqtt_pass, json["mqtt_pass"]);
}
else {
Serial.println("failed to load json config");
}
configFile.close();
}
}
}
}
else {
Serial.println("failed to mount FS");
}
//end read
// The extra parameters to be configured (can be either global or just in the setup)
// After connecting, parameter.getValue() will get you the configured value
// id/name placeholder/prompt default length
WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6);
WiFiManagerParameter custom_mqtt_topic("topic", "mqtt topic", mqtt_topic, 20);
WiFiManagerParameter custom_mqtt_ID("ID", "mqtt ID", mqtt_ID, 8);
WiFiManagerParameter custom_mqtt_user("user", "mqtt user", mqtt_user, 20);
WiFiManagerParameter custom_mqtt_pass("pass", "mqtt pass", mqtt_pass, 20);
//set config save notify callback
wifiManager.setSaveConfigCallback(saveConfigCallback);
//set static ip
// wifiManager.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
//add all your parameters here
wifiManager.addParameter(&custom_mqtt_server);
wifiManager.addParameter(&custom_mqtt_port);
wifiManager.addParameter(&custom_mqtt_topic);
wifiManager.addParameter(&custom_mqtt_ID);
wifiManager.addParameter(&custom_mqtt_user);
wifiManager.addParameter(&custom_mqtt_pass);
//set minimum quality of signal so it ignores AP's under that quality
//defaults to 8%
//wifiManager.setMinimumSignalQuality();
//sets timeout until configuration portal gets turned off
//useful to make it all retry or go to sleep
//in seconds
//wifiManager.setTimeout(120);
//fetches ssid and pass and tries to connect
//if it does not connect it starts an access point with the specified name
//here "AutoConnectAP"
//and goes into a blocking loop awaiting configuration
if (!wifiManager.autoConnect("AutoConnectFlowESP8266", "password")) {
Serial.println("failed to connect and hit timeout");
delay(3000);
//reset and try again, or maybe put it to deep sleep
ESP.reset();
delay(5000);
}
shouldSaveConfig = true;
//if you get here you have connected to the WiFi
Serial.println("connected to: )");
String ssid = WiFi.SSID();
String password = WiFi.psk();
Serial.print(ssid);
Serial.println(" ; ");
Serial.println(password);
//read updated parameters
strcpy(mqtt_server, custom_mqtt_server.getValue());
strcpy(mqtt_port, custom_mqtt_port.getValue());
strcpy(mqtt_topic, custom_mqtt_topic.getValue());
strcpy(mqtt_ID, custom_mqtt_ID.getValue());
strcpy(mqtt_user, custom_mqtt_user.getValue());
strcpy(mqtt_pass, custom_mqtt_pass.getValue());
// strcpy(blynk_token, custom_blynk_token.getValue());
//save the custom parameters to FS
if (shouldSaveConfig) {
Serial.println("saving config");
#ifdef ARDUINOJSON_VERSION_MAJOR >= 6
DynamicJsonDocument json(1024);
#else
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.createObject();
#endif
json["mqtt_server"] = mqtt_server;
json["mqtt_port"] = mqtt_port;
json["mqtt_topic"] = mqtt_topic;
json["mqtt_ID"] = mqtt_ID;
json["mqtt_user"] = mqtt_user;
json["mqtt_pass"] = mqtt_pass;
File configFile = SPIFFS.open(configFileName, "w");
if (!configFile) {
Serial.println("failed to open config file for writing");
}
#ifdef ARDUINOJSON_VERSION_MAJOR >= 6
serializeJson(json, Serial);
serializeJson(json, configFile);
#else
json.printTo(Serial);
json.printTo(configFile);
#endif
configFile.close();
//end save
}
wifiManager.getWLStatusString(wlan_status);
Serial.println();
Serial.print("WLan Status: ");
Serial.println(wlan_status);
if (wlan_status == 0) {
wifiManager.stopWebPortal();
wifiManager.stopConfigPortal();
}
Serial.println("local ip");
Serial.println(WiFi.localIP());
String topic_string(mqtt_topic);
String flowRate_out_s = topic_string + "/flowRate_out";
String FlowLiters_out_s = topic_string + "/FlowLiters_out";
String FlowMiliLiters_out_s = topic_string + "/FlowMiliLiters_out";
String m_perc_in_s = topic_string + "/m_perc_in";
String Ralais1_in_S = topic_string + "/Ralais1_in";
const char *flowRate_out = flowRate_out_s.c_str();
const char *FlowLiters_out = FlowLiters_out_s.c_str();
const char *FlowMiliLiters_out = FlowMiliLiters_out_s.c_str();
const char *m_perc_in = m_perc_in_s.c_str();
const char *Ralais1_in = Ralais1_in_S.c_str();
// client.setServer(mqtt_server, 12025);
String mqtt_prt_x_s(mqtt_port);
const uint16_t mqtt_port_x = strtol(mqtt_prt_x_s.c_str(), NULL, 10);
const char* mqtt_server_conn = mqtt_server;
client.setServer(mqtt_server_conn, mqtt_port_x);
Serial.println("MQTT Server startet with: ");
Serial.print(mqtt_server_conn);
Serial.print(" ; ");
Serial.println(mqtt_port_x);
client.setCallback(callback);
WiFi.setAutoReconnect(true);
WiFi.persistent(true);
pinMode(RelaisPin, OUTPUT);
pinMode(SENSOR, INPUT_PULLUP);
pinMode(resteButton, INPUT);
pulseCount = 0;
flowRate = 0.0;
flowMilliLitres = 0;
totalMilliLitres = 0;
previousMillis = 0;
attachInterrupt(digitalPinToInterrupt(SENSOR), pulseCounter, FALLING);
}
void callback(char* topic, byte * payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
String message = message + (char) payload[i]; // convert *byte to string
Serial.print(message);
}
Serial.println();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String mqttID(mqtt_ID);
String clientId = "ESP8266ClientFlow" + mqttID;
//clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
//client.publish("test1", "hello world");
// ... and resubscribe
percentageHumididy = client.subscribe(m_perc_in);
relais = client.subscribe(Ralais1_in);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
restebuttonstat = digitalRead(resteButton);
if (restebuttonstat == HIGH) {
reset_setting();
delay(5000);
wifiManager.reboot();
}
if (!client.connected()) {
reconnect();
}
client.loop();
currentMillis = millis();
if (currentMillis - previousMillis > interval)
{
pulse1Sec = pulseCount;
pulseCount = 0;
// Because this loop may not complete in exactly 1 second intervals we calculate
// the number of milliseconds that have passed since the last execution and use
// that to scale the output. We also apply the calibrationFactor to scale the output
// based on the number of pulses per second per units of measure (litres/minute in
// this case) coming from the sensor.
flowRate = ((1000.0 / (millis() - previousMillis)) * pulse1Sec) / calibrationFactor;
previousMillis = millis();
// Divide the flow rate in litres/minute by 60 to determine how many litres have
// passed through the sensor in this 1 second interval, then multiply by 1000 to
// convert to millilitres.
flowMilliLitres = (flowRate / 60) * 1000;
flowLitres = (flowRate / 60);
// Add the millilitres passed in this second to the cumulative total
totalMilliLitres += flowMilliLitres;
totalLitres += flowLitres;
// Print the flow rate for this second in litres / minute
Serial.print("Flow rate: ");
Serial.print(float(flowRate)); // Print the integer part of the variable
Serial.print("L/min");
Serial.print("\t"); // Print tab space
char FlowRate[10];
dtostrf(flowRate, 9, 2, FlowRate);
client.publish(flowRate_out, FlowRate);
// Print the cumulative total of litres flowed since starting
Serial.print("Output Liquid Quantity: ");
Serial.print(totalMilliLitres);
Serial.print("mL / ");
Serial.print(totalLitres);
Serial.println("L");
char FlowtotalLitres[10];
dtostrf(totalLitres, 9, 2, FlowtotalLitres);
client.publish(FlowLiters_out, FlowtotalLitres);
char FlowtotalMilliLitres[10];
dtostrf(totalMilliLitres, 9, 2, FlowtotalMilliLitres);
client.publish(FlowMiliLiters_out, FlowtotalMilliLitres);
}
Serial.print("Percentage humidity in: ");
Serial.println(percentageHumididy);
if (percentageHumididy < 50) {
digitalWrite(RelaisPin, HIGH);
Serial.println("Relais ON");
percentageHumididy = 60;
delay(5000);
}
else if (percentageHumididy > 50) {
digitalWrite(RelaisPin, LOW);
Serial.println("Relais OFF");
}
}
Edit: I know there are some other error but i think they are related to the formatting of the setup..
And i counted the brackets but did not find anything.
The auto formating is leading to the codestructure above..
thanks and nice day