/*
  Simple http clinet for influx 
  you need an ethernetclient 

  f41_ardu 04/2024 better now as Dr. Druck
  Start the simulstion and see the serial print statements
  Remove commeted code, adopt according your requirements 
  and implement your sensors. 

  Imorved exampls using an real sensor. 

*/

/* 
#include <SPI.h>
#include <Ethernet.h>

// replace the MAC address below by the MAC address printed on a sticker on the Arduino Shield 2
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(10, 40, 16, 23);
EthernetClient InFluxClient;
*/ 

#include "DHT.h"

#define DHTPIN 3     
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321

DHT dht(DHTPIN, DHTTYPE);

int    HTTP_PORT   = 6100; // replace by your port of the influxDB
char   HOST_NAME[] = "192.168.1.99"; // replace by your influx server IP
String influxServerIP = "192.168.1.99"; // replace by our influx server IP
 


String token = "replace by your token"; 
String organisation = "private"; 
String Bucket = "ArduinoTest";

void setup() {
  Serial.begin(9600);
  dht.begin();
/*
  // initialize the Ethernet shield using DHCP:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to obtaining an IP address using DHCP");
    while(true);
  }
*/ 
}

void loop() {
  
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();

  // Check if any reads failed and exit early (to try again).
  if (isnan(temperature) || isnan(humidity)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }
// this are sample data add your sensors and build your onwn sensor string
  String data = "TFAOutDoor,sensor_id=7c temperature="+String(temperature)+",humidity="+String(humidity);
  int dataLength = 0;
  String contLength = "Content-Length: ";
// dataLenght = data.lenght();
  contLength = contLength+=data.length();

  // Check if any reads failed and exit early (to try again).
  delay(5000);

  if (true) {
      Serial.println("Connected to server");
    // Construct and send the HTTP POST request
    // replace Serial by InfluxClient below
      Serial.println("POST /api/v2/write?org="+organisation+"&bucket="+Bucket+"+&precision=ns HTTP/1.1");
      Serial.println("Host: " + influxServerIP);
      Serial.println("Authorization: Token " + token);
      Serial.println(contLength);
      Serial.println("Content-Type: text/plain; charset=utf-8");
      Serial.println("Accept:  application/json");
      Serial.println(data);
      Serial.println();
      // replace Serial by InfluxClient above
      // Allow time for the server to respond

    delay(500);
/*
while (Client.available()) {
      char c = Client.read();
      Serial.write(c);
    }

    Client.stop();
  } else {
    Serial.println("Connection failed");
  }
*/

  }

}