#include <ESP32Servo.h>
#include <HX711.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <WiFi.h>
#include <PubSubClient.h>
Adafruit_SSD1306 display(128, 64, &Wire, -1);
HX711 scale;
WiFiClient espClient;
PubSubClient client(espClient);
Servo myservo;
uint8_t sudut = 0;
uint16_t berat = 0;
uint16_t berat1 = 0;
String pesan = "";
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "mqtt-dashboard.com";
char data1;
int j = 0;
char data2[4];
void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print(F("Connecting to "));
  Serial.println(ssid);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(F("."));
  }
  //  randomSeed(micros());
  Serial.println(F("WiFi connected"));
  Serial.println(F("IP address: "));
  Serial.println(WiFi.localIP());
}
void reconnect() {
  while (!client.connected()) {
    Serial.print(F("Attempting MQTT connection..."));
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);
    if (client.connect(clientId.c_str())) {
      Serial.println(F("connected"));
      client.subscribe("ebpro_wokwi/servo");
    } else {
      Serial.print(F("failed, rc="));
      Serial.print(client.state());
      Serial.println(F(" try again in 5 seconds"));
      delay(5000);
    }
  }
}
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print(F("Message arrived ["));
  Serial.print(topic);
  Serial.print(F("] "));
  for (int i = 0; i < length; i++) {
    data1 = ((char)payload[i]);
    if (data1 >= '0' && data1 <= '9') {
      data2[j] = data1;
      j++;
    }
  }
  sudut = atoi(data2);
  j = 0;
  memset(data2, 0, sizeof(data2));
  myservo.write(sudut);
  Serial.println(sudut);
  tampil();
}
void setup() {
  Serial.begin(115200);
  myservo.attach(5);
  scale.begin(19, 18);//DT,SCK
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for (;;);
  }
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}
void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  berat = round(scale.get_units() * 50 / 21); //gram
  pesan = "{\"gram\":" + String(berat) + "}";
  if (berat != berat1) {
    Serial.print(F("Publish message: "));
    Serial.println(pesan);
    client.publish("wokwi_ebpro/berat", pesan.c_str());
    tampil();
  }
  berat1 = berat;
}
void tampil() {
  display.clearDisplay();
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(0, 0);
  display.print("Sudut:");
  display.print(sudut);
  display.print(char(247));
  display.setCursor(0, 25);
  display.print("Berat:");
  display.setCursor(50, 45);
  display.print(berat / 1000.0, 1);
  display.print("kg");
  display.display();
}