-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
82 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,84 @@ | ||
pip install paho-mqtt | ||
|
||
import paho.mqtt.client as mqtt | ||
|
||
#include <SPI.h> | ||
#include <WiFiNINA.h> | ||
#include <PubSubClient.h> | ||
|
||
// 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; | ||
} |