Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Dependencies: esp8266-driver MQTT
Revision 97:d87239079f29, committed 2019-08-23
- Comitter:
- UlricL
- Date:
- Fri Aug 23 13:13:42 2019 +0000
- Parent:
- 96:e0963326d853
- Commit message:
- Jnu726wifiMQTT
Changed in this revision
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/MQTT.lib Fri Aug 23 13:13:42 2019 +0000 @@ -0,0 +1,1 @@ +https://os.mbed.com/teams/mqtt/code/MQTT/#9cff7b6bbd01
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/esp8266-driver.lib Fri Aug 23 13:13:42 2019 +0000 @@ -0,0 +1,1 @@ +https://os.mbed.com/users/UlricL/code/esp8266-driver/#8609148e2116
--- a/main.cpp Mon Feb 25 16:41:30 2019 +0000
+++ b/main.cpp Fri Aug 23 13:13:42 2019 +0000
@@ -15,6 +15,14 @@
*/
#include "mbed.h"
+#include "MQTTNetwork.h"
+#include "MQTTmbed.h"
+#include "MQTTClient.h"
+#include "ESP8266Interface.h"
+
+const char* hostname = "172.20.16.92"; //修改服务器IP及端口号
+int port = 1883;
+
WiFiInterface *wifi;
@@ -93,7 +101,7 @@
}
printf("\nConnecting to %s...\n", MBED_CONF_APP_WIFI_SSID);
- int ret = wifi->connect(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA_WPA2);
+ int ret = wifi->connect("OPPO_R11s", "12345678", NSAPI_SECURITY_WPA_WPA2);
if (ret != 0) {
printf("\nConnection error: %d\n", ret);
return -1;
@@ -109,4 +117,34 @@
wifi->disconnect();
printf("\nDone\n");
+ MQTTNetwork mqttNetwork(network);
+MQTT::Client<MQTTNetwork, Countdown> client(mqttNetwork);
+
+int rc = mqttNetwork.connect(hostname, port);
+
+ MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
+ data.MQTTVersion = 3;
+ data.clientID.cstring = "mbed-sample";
+ data.username.cstring = "testuser";
+ data.password.cstring = "testpassword";
+ if ((rc = client.connect(data)) != 0)
+ printf("rc from MQTT connect is %d\r\n", rc);
+
+if ((rc = client.subscribe(“sensor”, MQTT::QOS2, messageArrived)) != 0) //订阅消息
+ printf("rc from MQTT subscribe is %d\r\n", rc);
+while(true){
+ client.yield(100); //在循环中一直等待接收消息
}
+void messageArrived(MQTT::MessageData& md) //消息接收回调函数
+{
+ MQTT::Message &message = md.message;
+ if(((char*)message.payload)[0] == '0') //解析服务器消息
+ {
+ led = 0; //处理消息开关灯,可在此修改为其他控制指令
+ }
+ else
+{
+led = 1;
+ }
+}
+}