0

I have my code written for connecting an esp32 to influxdb. Im utilizing the wifimanager library to set my wifi credentials without hardcoding. I would like to set up custom text boxes to fill in the necessary credential required to connect to influxdb. I decided the best way to acomplish this would be to create a json document and save the information to the flash memory. I cant figure out how to implement my save json strings into the where i would define my influxdb bucket and token. any help would be appreciated.

I have posted my code below. I have figure out how to creat the custome text boxs and save them to the memory i just cant figure out how to use those values as my Influxdb bucket and token

#if defined(ESP32)
#include <WiFiMulti.h>
WiFiMulti wifiMulti;
#define DEVICE "ESP32"
#elif defined(ESP8266)
#include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti wifiMulti;
#define DEVICE "ESP8266"
#endif
#define ESP_DRD_USE_SPIFFS true
// WiFi Library
#include <WiFi.h>
// File System Library
#include <FS.h>
// SPI Flash Syetem Library
#include <SPIFFS.h>
// WiFiManager Library
#include <WiFiManager.h>
// Arduino JSON library
#include <ArduinoJson.h>
 
// JSON configuration file
#define JSON_CONFIG_FILE "/test_config.json"

// Influx Libraries
#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>

// WiFi AP SSID
//#define WIFI_SSID ""
// WiFi password
//#define WIFI_PASSWORD ""
// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries)
#define INFLUXDB_URL ""
// InfluxDB v2 organization id (Use: InfluxDB UI -> User -> About -> Common Ids )
#define INFLUXDB_ORG ""
#define INFLUXDB_TOKEN ""
#define INFLUXDB_BUCKET ""

// Set timezone string according to https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
// Examples:
//  Pacific Time: "PST8PDT"
//  Eastern: "EST5EDT"
//  Japanesse: "JST-9"
//  Central Europe: "CET-1CEST,M3.5.0,M10.5.0/3"
#define TZ_INFO "PST8PDT"

// InfluxDB client instance with preconfigured InfluxCloud certificate
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);

unsigned long previousMillis = 0;
unsigned long interval = 30000;

const int ledPin = 17;
const int ledPin2 = 16;
const int buttonPin = 4; // the number of the pushbutton pin
int buttonState = 1; 

// Flag for saving data
bool shouldSaveConfig = true;
 
// Variables to hold data from custom textboxes
char apiString[90] = "INFLUX_TOKEN";
char bucketString[34] = "INFLUX_BUCKET";

// Define WiFiManager Object
WiFiManager wm;
 
void saveConfigFile()
// Save Config in JSON format
{
  Serial.println(F("Saving configuration..."));
  
  // Create a JSON document
  StaticJsonDocument<512> json;
  json["apiString"] = apiString;
  json["bucketString"] = bucketString;
 
  // Open config file
  File configFile = SPIFFS.open(JSON_CONFIG_FILE, "w");
  if (!configFile)
  {
    // Error, file did not open
    Serial.println("failed to open config file for writing");
  }
 
  // Serialize JSON data to write to file
  serializeJsonPretty(json, Serial);
  if (serializeJson(json, configFile) == 0)
  {
    // Error writing file
    Serial.println(F("Failed to write to file"));
  }
  // Close file
  configFile.close();
}
 
bool loadConfigFile()
// Load existing configuration file
{
  // Uncomment if we need to format filesystem
  //SPIFFS.format();
 
  // Read configuration from FS json
  Serial.println("Mounting File System...");
 
  // May need to make it begin(true) first time you are using SPIFFS
  if (SPIFFS.begin(false) || SPIFFS.begin(true))
  {
    Serial.println("mounted file system");
    if (SPIFFS.exists(JSON_CONFIG_FILE))
    {
      // The file exists, reading and loading
      Serial.println("reading config file");
      File configFile = SPIFFS.open(JSON_CONFIG_FILE, "r");
      if (configFile)
      {
        Serial.println("Opened configuration file");
        StaticJsonDocument<512> json;
        DeserializationError error = deserializeJson(json, configFile);
        serializeJsonPretty(json, Serial);
        if (!error)
        {
          Serial.println("Parsing JSON");
 
          strcpy(apiString, json["apiString"]);
          strcpy(bucketString, json["bucketString"]);
 
          return true;
        }
        else
        {
          // Error loading JSON data
          Serial.println("Failed to load json config");
        }
      }
    }
  }
  else
  {
    // Error mounting file system
    Serial.println("Failed to mount FS");
  }
 
  return false;

}
 
 
void saveConfigCallback()
// Callback notifying us of the need to save configuration
{
  Serial.println("Should save config");
  shouldSaveConfig = true;
}
 
void configModeCallback(WiFiManager *myWiFiManager)
// Called when config mode launched
{
  Serial.println("Entered Configuration Mode");
 
  Serial.print("Config SSID: ");
  Serial.println(myWiFiManager->getConfigPortalSSID());
 
  Serial.print("Config IP Address: ");
  Serial.println(WiFi.softAPIP());
}

void setup() { 
  

 {
    // Setup Serial monitor

  // Change to true when testing to force configuration every time we run
  bool forceConfig = false;
 
  bool spiffsSetup = loadConfigFile();

  if (!spiffsSetup) 
  {
    Serial.println(F("Forcing config mode as there is no saved config"));
    forceConfig = true;}
 
  // Explicitly set WiFi mode
  WiFi.mode(WIFI_STA);

  Serial.begin(115200);

  wm.setDebugOutput(false);
  
  pinMode(ledPin, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  
  digitalWrite(ledPin, HIGH);
  digitalWrite(ledPin2, LOW);
  delay(15000);
  
  wm.setConnectTimeout(60);
  wm.setConnectRetries(10);

// initialize the pushbutton pin as an input
 pinMode(buttonPin, INPUT);
 
  // Reset settings (only for development)
  //wm.resetSettings();
 
  // Set config save notify callback
  wm.setSaveConfigCallback(saveConfigCallback);

  // Set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
 wm.setAPCallback(configModeCallback);
 
 
  // Custom elements
 
  // Text box (String) - 90 characters maximum
  WiFiManagerParameter CUSTOM_INFLUX_TOKEN("api_key", "API_TOKEN", apiString, 90);
  WiFiManagerParameter CUSTOM_INFLUX_BUCKET("bucket", "INFLUX_BUCKET", bucketString, 34); 
 
  // Add all defined parameters
  wm.addParameter(&CUSTOM_INFLUX_TOKEN);
  wm.addParameter(&CUSTOM_INFLUX_BUCKET);

  if (forceConfig)
    // Run if we need a configuration
  {
    if (!wm.startConfigPortal("MJRTM_AP", "password"))
    {
      Serial.println("failed to connect and hit timeout");
      delay(3000);
      //reset and try again, or maybe put it to deep sleep
      ESP.restart();
      delay(5000);
    }
  }
  else
  {
    if (!wm.autoConnect("MJRTM_AP", "password"))
    {
      Serial.println("failed to connect and hit timeout");
      delay(3000);
      // if we still have not connected restart and try all over again
      ESP.restart();
      delay(5000);
    }


  }

{if (WiFi.status() != WL_CONNECTED) {
// turn LED on
digitalWrite(ledPin2, LOW); }
else { // turn LED off
digitalWrite(ledPin2, HIGH);
}
 }

  // If we get here, we are connected to the WiFi
 
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  // Lets deal with the user config values

  // Copy the string value
  strncpy(apiString, CUSTOM_INFLUX_TOKEN.getValue(), sizeof(apiString));
  Serial.print("INFLUX_TOKEN: ");
  Serial.println(apiString);
  strncpy(bucketString, CUSTOM_INFLUX_BUCKET.getValue(), sizeof(bucketString));
  Serial.print("INFLUX_BUCKET: ");
  Serial.println(bucketString);

  Serial.print ("INFLUXDB BUCKET:");
  Serial.println(INFLUXDB_BUCKET);

  // Save the custom parameters to FS
  if (shouldSaveConfig)
  {
    saveConfigFile();
  }
 
  // Accurate time is necessary for certificate validation and writing in batches
  // For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/
  // Syncing progress and the time will be printed to Serial.
  timeSync(TZ_INFO, "pool.ntp.org", "time.nis.gov");

  // Check server connection
  if (client.validateConnection()) {
    Serial.print("Connected to InfluxDB: ");
    Serial.println(client.getServerUrl());
  } else {
    Serial.print("InfluxDB connection failed: ");
    Serial.println(client.getLastErrorMessage());
  }
  
  adcMax = 4095.0; // ADC resolution 12-bit (0-4095)
  Vs = 3.3;        // supply voltage  Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
  Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
 }
}
  • "i just cant figure out how to use those values", what values? – hcheung Apr 01 '23 at 05:45
  • The JSON strings that I'm saving to the flash memory of the board. I'm saving the influx bucket and api key from the custom text boxes to the board but I'm not sure how then used those strings as an input for my actual influx bucket and api token. – ndeegan Apr 02 '23 at 12:42
  • You did not answer the question, what values? what JSON strings? You are the only one who know what in your "custom text boxes". If you can't articulate your problem, no one can give you an answer. – hcheung Apr 03 '23 at 01:39
  • Sorry I'm fairly new to coding and still trying to understand certain concepts. I have 2 JSON strings apiString & bucketString. The custom text boxes are generated on start up in a web browser when a wifi network is needed. There I eneter in my infludb bucket and influxdb api token. once saved those values are converted to the JSON strings and saved to the flash memory of the esp32 using the spiffs filiing system. What i cant seem to figure out is how to then inject those JSON strings into the area of my code where I define the Infludb bucket and token for the client library. – ndeegan Apr 03 '23 at 16:32

0 Answers0