#include <WiFi.h>
#include <PubSubClient.h>
#include <ESP32Servo.h>
#include <ArduinoJson.h>
const char* ssid = "Wokwi-GUEST"; // Wi-Fi SSID
const char* password = ""; // Wi-Fi password
const char* mqtt_server = "test.mosquitto.org"; // MQTT broker
WiFiClient espClient;
PubSubClient client(espClient);
Servo myServo;
int receivedValue = 0;
const int servoPin = 18;
int currentAngle = 0;
int targetAngle = 0;
int mqttPort = 1883;
// Топики
const char* topic_prefix = "ATPEZLR8/Client1/";
const char* target_topic = "ATPEZLR8/Client1/servo/target_angle";
const char* current_topic = "ATPEZLR8/Client1/servo/current_angle";
void callback(char* topic, byte* payload, unsigned int length) {
String message;
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
Serial.println();
if (String(topic) == target_topic) {
targetAngle = message.toInt();
servo.write(targetAngle);
Serial.print("Parsed angle: ");
Serial.println(receivedValue);
}
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESP32Client")) {
Serial.println("connected");
client.subscribe(target_topic);
Serial.println("Subscribed to:");
Serial.println(target_topic);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
myServo.attach(servoPin, 500, 2400);
myServo.write(currentAngle);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
if (currentAngle != targetAngle) {
currentAngle = targetAngle;
myServo.write(currentAngle);
Serial.print("Servo moved to angle: ");
Serial.println(currentAngle);
// Отправка текущего угла в MQTT
char buffer[10];
snprintf(buffer, sizeof(buffer), "%d", currentAngle);
client.publish(current_topic, buffer);
}
delay(100);
}