嗯,好的 谢谢
用的Arduino ide编写的,网上的帖子抄的
#include <WiFi.h>
#include "PubSubClient.h"
#include <WiFiUdp.h>
#include "ESP32BLEAdvertise.h"
const char* ssid = "C-T";
const char* password = "111111";
//#define ID_MQTT "64e26601a9f63aa70"
const char* topic = "GIMITYY";
const int B_led = 2;
bool Turned = false;;
const char* mqtt_server = "192.168.31.80";
const int mqtt_server_port = 1883;
const char* mqtt_username = "cc";
const char* mqtt_password = "password";
WiFiClient espClient;
PubSubClient client(espClient);
SimpleBLE bleadv;
//灯光函数及引脚定义
void turnOn();
void turnOff();
WiFiUDP Udp;
IPAddress remote_IP(192, 168, 31, 143);
unsigned int remoteUdpPort = 16735;
unsigned int remoteUdpPortFZ = 16750;
const char* Keyword = "KEYPRESSES:116";
const char* KeywordFZ = {"{"action":20000,"controlCmd":{"delayTime":0,"mode":6,"time":0,"type":0},"msgid":"2"}"};
void setup_wifi() {
delay(10);
Serial.println();
Serial.print(F ("Connecting to ") );
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(F (".") );
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print(F ("Topic:") );
Serial.println(topic);
String msg = "";
for (int i = 0; i < length; i++) {
msg += (char)payload[i];
}
Serial.print(F ("Msg:") );
Serial.println(msg);
if (msg == "on") {
turnOn();
Turned = true;
} else if (msg == "off") {
turnOff();
Turned = false;
}
msg = "";
}
void reconnect() {
while (!client.connected()) {
Serial.print(F ("Attempting MQTT connection...") );
if (client.connect(ID_MQTT)) {
Serial.println("connected");
Serial.print(F ("subscribe:") );
Serial.println(topic);
client.subscribe(topic);
} else {
Serial.print(F ("failed, rc=") );
Serial.print(F (client.state()) );
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void setup() {
pinMode(B_led, OUTPUT);
digitalWrite(B_led, LOW);
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, mqtt_server_port);
client.setCallback(callback);
}
void loop() {
int i = 1;
if (!client.connected()) {
reconnect();
}
else
{
if (Turned)
{
bleadv.begin();
uint8_t data[] = {0x46,0x00,0x28,0x68,0xe9,0x68,0xb2,0x24,0x40,0xff,0xff,0xff,0x30,0x43,0x52,0x4b,0x54,0x4d};
bleadv.advertise(data, 18);
delay(5000);
}
else
{
bleadv.end();
}
}
client.loop();
}
void turnOn() {
digitalWrite(B_led, HIGH);
}
void turnOff() {
digitalWrite(B_led, LOW);
Udp.beginPacket(remote_IP, remoteUdpPortFZ);
String str_cnt(KeywordFZ);
Udp.print(str_cnt);
Udp.endPacket();
}
|