File size: 1,802 Bytes
034ba67 | 1 2 3 4 5 | {"type": "session", "harness": "deepseek-harness", "id": "sys-0020", "name": "ESP32 WiFi and MQTT"}
{"type": "message", "message": {"role": "system", "content": "You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing code, identify bugs, security issues, and performance problems. You have deep knowledge of C/C++, Windows API, Python, and many other technologies."}}
{"type": "message", "message": {"role": "user", "content": "How do I connect ESP32 to WiFi and MQTT?"}}
{"type": "message", "message": {"role": "assistant", "content": "```cpp\n#include <WiFi.h>\n#include <PubSubClient.h>\n\nconst char* ssid = \"MyWiFi\";\nconst char* password = \"password\";\nconst char* mqtt_server = \"broker.example.com\";\n\nWiFiClient espClient;\nPubSubClient client(espClient);\n\nvoid setup_wifi() {\n WiFi.begin(ssid, password);\n while (WiFi.status() != WL_CONNECTED) {\n delay(500);\n }\n}\n\nvoid callback(char* topic, byte* payload, unsigned int length) {\n String message;\n for (int i = 0; i < length; i++) {\n message += (char)payload[i];\n }\n Serial.println(\"Message: \" + message);\n}\n\nvoid reconnect() {\n while (!client.connected()) {\n if (client.connect(\"ESP32Client\")) {\n client.subscribe(\"sensors/#\");\n client.publish(\"sensors/status\", \"online\");\n }\n }\n}\n\nvoid loop() {\n if (!client.connected()) reconnect();\n client.loop();\n\n // Publish sensor data\n float temp = readTemperature();\n String payload = String(temp);\n client.publish(\"sensors/temperature\", payload.c_str());\n delay(5000);\n}\n```"}}
|