const int pinRed = 27;
const int pinGreen = 26;
const int pinBlue = 25;
const int pinServo = 18;
const int pinPot = 14;

#include <WiFi.h>
#include <ESP32Servo.h>
#include <MQTT.h>
#include "function.h"

const char ssid[] = "Wokwi-GUEST";
const char pass[] = "";

WiFiClient net;
MQTTClient client;
Servo servo;

int pot;

void connect(){
  rgb(1,0,0);
  while(WiFi.status() != WL_CONNECTED){
    delay(200);
  }
  rgb(0,1,0);

  while(!client.connect("clientid-nya")){
    delay(200);
  }
  rgb(0,0,1);
}

void setup() {
  pinMode(pinRed, OUTPUT);
  pinMode(pinGreen, OUTPUT);
  pinMode(pinBlue, OUTPUT);
  pinMode(pinPot, INPUT);
  servo.attach(pinServo, 500, 2400);

  WiFi.begin(ssid, pass);
  client.begin("broker.emqx.io", net);

  connect();
}

void loop() {
  pot = analogRead(pinPot);
  int posServo = map(pot, 0,4095, 0,180);
  servo.write(posServo);

  client.publish("nusabot/pot", String(pot), true, 1);

  delay(10);
}