#include <WiFiClientSecure.h>
#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
const char* ssid = "ssid";
const char* password = "password";
const char* mqtt_server = "printers_ip"; // Replace with your P1P's IP address
const int mqtt_port = 8883;
const char* mqtt_user = "username";
const char* mqtt_password = "access_code"; // Replace with your LAN access code
const char* serial_number = "serialnumber"; // Replace with your printer's serial number
const char* topic_subscribe = "device/serial_number/report";
const char* topic_publish = "device/serial_number/request";
WiFiClientSecure espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
setupWiFi();
espClient.setInsecure();
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
void setupWiFi() {
Serial.print("Connecting to WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected");
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message received on topic: ");
Serial.println(topic);
String message;
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
Serial.println("Message content: " + message);
DynamicJsonDocument doc(1024);
DeserializationError error = deserializeJson(doc, message);
if (!error) {
Serial.println("Parsed JSON message:");
serializeJsonPretty(doc, Serial);
Serial.println();
if (doc.containsKey("print")) {
JsonObject print = doc["print"];
if (print.containsKey("command") && print["command"] == "push_status") {
Serial.println("Received status update:");
if (print.containsKey("bed_temper")) {
float bedTemp = print["bed_temper"].as<float>();
Serial.print("Bed Temperature: ");
Serial.println(bedTemp);
}
if (print.containsKey("nozzle_temper")) {
float nozzleTemp = print["nozzle_temper"].as<float>();
Serial.print("Nozzle Temperature: ");
Serial.println(nozzleTemp);
}
if (print.containsKey("wifi_signal")) {
String wifiSignal = print["wifi_signal"].as<String>();
Serial.print("WiFi Signal: ");
Serial.println(wifiSignal);
}
if (print.containsKey("sequence_id")) {
String sequenceId = print["sequence_id"].as<String>();
Serial.print("Sequence ID: ");
Serial.println(sequenceId);
}
// Add homing status check here
if (print.containsKey("homing_status")) {
String homingStatus = print["homing_status"].as<String>();
Serial.println("Homing Status: " + homingStatus);
}
}
}
} else {
Serial.print("Failed to parse JSON: ");
Serial.println(error.c_str());
}
}
void reconnect() {
int retries = 0;
while (!client.connected() && retries < 5) { // Try to connect up to 5 times
Serial.print("Attempting MQTT connection...");
if (client.connect("ESP32Client", mqtt_user, mqtt_password)) {
Serial.println("connected");
// Subscribe to the response topic
if (client.subscribe(topic_subscribe)) {
Serial.println("Subscribed to topic: " + String(topic_subscribe));
} else {
Serial.println("Failed to subscribe to topic: " + String(topic_subscribe));
}
startHoming(); // Send homing command after connecting
queryPosition();
} else {
retries++;
int error = client.state();
Serial.print("MQTT connection failed! Error code = ");
Serial.println(error);
switch (error) {
case -4:
Serial.println("MQTT_CONNECTION_TIMEOUT");
break;
case -3:
Serial.println("MQTT_CONNECTION_LOST");
break;
case -2:
Serial.println("MQTT_CONNECT_FAILED");
break;
case -1:
Serial.println("MQTT_DISCONNECTED");
break;
case 1:
Serial.println("MQTT_CONNECT_BAD_PROTOCOL");
break;
case 2:
Serial.println("MQTT_CONNECT_BAD_CLIENT_ID");
break;
case 3:
Serial.println("MQTT_CONNECT_UNAVAILABLE");
break;
case 4:
Serial.println("MQTT_CONNECT_BAD_CREDENTIALS");
break;
case 5:
Serial.println("MQTT_CONNECT_UNAUTHORIZED");
break;
default:
Serial.println("Unknown error code.");
break;
}
delay(5000); // Retry after a delay
}
}
if (retries >= 5) {
Serial.println("Failed to connect to MQTT after multiple attempts. Restarting ESP32...");
ESP.restart(); // Restart ESP32 if unable to connect
}
}
void startHoming() {
StaticJsonDocument<200> doc;
// Construct the payload for the homing command
doc["command"] = "G_code"; // Command type for G-code commands
doc["param"] = "G28"; // G-code for homing all axes
doc["sequence_id"] = String(millis()); // Unique sequence ID for tracking
doc["user_id"] = serial_number; // Printer's serial number
// Serialize the JSON payload into a string
String jsonString;
serializeJson(doc, jsonString);
// Print debug information
Serial.println("Publishing Homing Command:");
Serial.println("Topic: " + String(topic_publish));
Serial.println("Payload: " + jsonString);
// Publish the JSON payload to the MQTT topic
bool published = client.publish(topic_publish, jsonString.c_str(), true);
if (published) {
Serial.println("✅ Homing command sent successfully.");
} else {
Serial.println("❌ Failed to send homing command.");
}
}
void queryPosition() {
StaticJsonDocument<200> doc;
doc["command"] = "get_position"; // Hypothetical command for querying position
doc["sequence_id"] = String(millis());
doc["user_id"] = serial_number;
String jsonString;
serializeJson(doc, jsonString);
Serial.println("Publishing Position Query:");
Serial.println("Topic: " + String(topic_publish));
Serial.println("Payload: " + jsonString);
bool published = client.publish(topic_publish, jsonString.c_str(), true);
if (published) {
Serial.println("✅ Position query sent successfully.");
} else {
Serial.println("❌ Failed to send position query.");
}
}
This code connects an ESP32 to a 3D printer via MQTT, allowing remote monitoring and control. It sends homing commands (G28) and queries printer status, handling responses in JSON format. The code includes WiFi setup, MQTT connection management, and error handling.
The ESP32-S3 WROOM Freenove, successfully sends MQTT commands (like G28 ) to the printer, but nothing happens on the printer’s end. It seems the commands are reaching the broker but not being executed by the printer. Possible causes include incorrect command format, printer configuration issues, or limitations in MQTT command execution support. Any ideas or similar experiences?
im using a p1p running firmware version 1.07. and using arduino studio