#include <WiFi.h>               // For Pico W WiFi
#include <PubSubClient.h>        // For MQTT

// Replace with your network credentials
const char* ssid = "Wokwi-GUEST";
const char* password = " ";

// Replace with your MQTT broker details
const char* mqtt_server = "broker.emqx.io";  // Example public broker
const int mqtt_port = 1883;                     // Default MQTT port
const char* topic1 = "parkingir/slot1";      // Topic to publish sensor data
const char* topic2 = "parkingir/slot2"; 

WiFiClient espClient;
PubSubClient client(espClient);

// Define IR sensor pins
const int ir1 = 2;
const int ir2 = 3;

String sv1,sv2,sv3,sv4,pv1,pv2,pv3,pv4;

void setup() {
  Serial1.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
  pinMode(ir1, INPUT);
  pinMode(ir2, INPUT);

}

void setup_wifi() {
  delay(10);
  Serial1.println();
  Serial1.print("Connecting to ");
  Serial1.println(ssid);

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial1.print(".");
  }

  Serial1.println("");
  Serial1.println("WiFi connected");
  Serial1.println("IP address: ");
  Serial1.println(WiFi.localIP());
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial1.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "PicoWClient-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial1.println("connected");
    } else {
      Serial1.print("failed, rc=");
      Serial1.print(client.state());
      Serial1.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  
  // Read IR sensor data
  int ir1Value = digitalRead(ir1);
  int ir2Value = digitalRead(ir2);
 
  sv1=pv1;
  sv2=pv2;
  sv3=pv3;
  sv4=pv4;
  pv1=ir1Value;
  pv2=ir2Value;
 
  if(sv1!=pv1){
  Serial1.print("Publishing message: ");
  String payload = "ir1_"+pv1;
  Serial1.println(payload);
  client.publish(topic1, pv1.c_str());
  }
  if(sv2!=pv2){
  Serial1.print("Publishing message: ");
  String payload = "ir2_"+pv2;
  Serial1.println(payload);
  client.publish(topic2, pv2.c_str());
  }

  delay(100); // Adjust delay based on desired publishing frequency
 // client.loop();
}