diff --git a/Lvs b/Lvs index 4547564..5de7284 100644 --- a/Lvs +++ b/Lvs @@ -1,3 +1,84 @@ pip install paho-mqtt - import paho.mqtt.client as mqtt + +#include +#include +#include + +// WiFi设置 +const char* ssid = "your_ssid"; +const char* password = "your_password"; + +// MQTT服务器设置 +const char* mqtt_server = "mqtt.example.com"; +const int mqtt_port = 1883; +const char* mqtt_topic = "door/window/status"; + +WiFiClient espClient; +PubSubClient client(espClient); + +void callback(char* topic, byte* payload, unsigned int length){ + +} + +void Reconnect() { + while (!client.connected()) { + Serial.print("Attempting MQTT connection..."); + if (client.connect("ArduinoClient")) { + Serial.println("connected"); + } else { + Serial.print("failed, rc="); + Serial.print(client.state()); + Serial.println(" try again in 5 seconds"); + delay(5000); + } + } +} + +void SetupWifi() { + delay(10); + Serial.print("Connecting to "); + Serial.println(ssid); + WiFi.begin(ssid, password); + + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + + Serial.println(""); + Serial.println("WiFi connected"); + Serial.print("IP address: "); + Serial.println(WiFi.localIP()); +} + +void setup() { + Serial.begin(115200); + setup_wifi(); + client.setServer(mqtt_server, mqtt_port); + client.setCallback(callback); +} + +void loop() { + bool doorIsOpen = readDoorSensor(); + + if (doorIsOpen) { + char msg[50]; + sprintf(msg, "OPEN"); + client.publish(mqtt_topic, msg); + } + + + if (!client.connected()) { + reconnect(); + } + client.loop(); + + delay(1000); +} + + +bool readDoorSensor() { + + return digitalRead(2) == HIGH; +}