#include <WiFi.h>  
#include <PubSubClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS 32
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "test.mosquitto.org";

WiFiClient Esp_Temp;
PubSubClient client(Esp_Temp);

void setup_wifi() { 
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.mode(WIFI_STA); 
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) { 
    delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
void reconnect() { 
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect("Esp_Temp")) {
      Serial.println("Connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }}
}

void setup() {
  pinMode(2, OUTPUT);     
  Serial.begin(115200);
  setup_wifi(); 
  client.setServer(mqtt_server, 1883);
  sensors.begin();
}

void Temp(){
  sensors.requestTemperatures();
  float tempC = sensors.getTempCByIndex(0);
  float tempF = sensors.getTempFByIndex(0);
  client.publish("TemperaturaC",String(tempC).c_str());
  client.publish("TemperaturaF",String(tempF).c_str());
  delay(1000);
    Serial.print(tempC);
  Serial.println("ºC Temp/DS18B20");
  Serial.print(tempF);
  Serial.println("ºF Temp/DS18B20");
  delay(5000);
}

void led_conexao(){
    if(WiFi.status() == WL_CONNECTED)
    digitalWrite(2,HIGH);
    else
    digitalWrite(2,LOW);
}

void loop() {
    reconnect();
    led_conexao();
    Temp();

  }