Android、ESP32、ESP8266的mqtt通信

Android

activity_main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"android:orientation="vertical"><TextViewandroid:id="@+id/recvTxt"android:layout_width="match_parent"android:layout_height="600dp"android:text=""app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /><Buttonandroid:id="@+id/onBtn"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="開燈" /><Buttonandroid:id="@+id/offBtn"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="關燈" /></LinearLayout>
AndroidManifest
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
MainActivity
package com.example.myapplication;
/*
* https://repo.eclipse.org/content/repositories/paho-releases/org/eclipse/paho/
* https://repo.eclipse.org/content/repositories/paho-releases/org/eclipse/paho/org.eclipse.paho.client.mqttv3/1.2.5/
* 下載org.eclipse.paho.client.mqttv3-1.2.5.jar文件
* 將下載的jar包復制至項目libs目錄下,并右擊mqtt jar包 ADD As Libray.. ,將mqtt jar包導入庫文件中。
* */
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;public class MainActivity extends AppCompatActivity {private String host = "tcp://broker.emqx.io:1883";private String userName = "dsx_phone";private String passWord = "dsx_phone_pwd";private String mqtt_id ="dsx_phone_001";private MqttClient client;private String subTopic = "dsx_phone"; //訂閱的主題  接收內容private String sendTopic = "dsx_esp8266";//發送的主題private MqttConnectOptions options;private TextView recvTxt;private Button onBtn,offBtn;MyHandler myHandler;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);recvTxt = findViewById(R.id.recvTxt);onBtn = findViewById(R.id.onBtn);offBtn = findViewById(R.id.offBtn);myHandler = new MyHandler();connectServer();onBtn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {publishMsg(sendTopic,"on");}});offBtn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {publishMsg(sendTopic,"off");}});}private void connectServer(){try {client = new MqttClient(host, mqtt_id, new MemoryPersistence());options = new MqttConnectOptions();options.setCleanSession(true);options.setUserName(userName);options.setPassword(passWord.toCharArray());options.setConnectionTimeout(10);options.setKeepAliveInterval(20);client.setCallback(new MqttCallback() {@Overridepublic void connectionLost(Throwable throwable) {//重新連接}@Overridepublic void messageArrived(String s, MqttMessage mqttMessage) throws Exception {//收到消息Message msg = new Message();msg.what = 2;msg.obj = s + "------" + mqttMessage.toString();myHandler.sendMessage(msg);}@Overridepublic void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {//發送完成后執行到這里Message msg = new Message();msg.what = 4;msg.obj = "Publish OK".toString();myHandler.sendMessage(msg);}});new Thread(new Runnable() {@Overridepublic void run() {try {if(!(client.isConnected())){client.connect(options);Message msg = new Message();msg.what = 1;msg.obj = "Connect Server Success".toString();myHandler.sendMessage(msg);publishMsg(sendTopic,"我是來自手機端的消息!");}}catch (Exception e){e.printStackTrace();Message msg = new Message();msg.what = 3;msg.obj = "Connect Server Fail".toString();myHandler.sendMessage(msg);}}}).start();} catch (MqttException e) {e.printStackTrace();throw new RuntimeException(e);}}private void publishMsg(String send_topic,String msg){if(client == null || !(client.isConnected())){return;}MqttMessage mqtt_msg = new MqttMessage();mqtt_msg.setPayload(msg.getBytes());try {client.publish(send_topic,mqtt_msg);} catch (MqttException e) {e.printStackTrace();throw new RuntimeException(e);}}class MyHandler extends Handler{@Overridepublic void handleMessage(@NonNull Message msg) {super.handleMessage(msg);switch (msg.what){case 1:recvTxt.setText(msg.obj.toString());Toast.makeText(MainActivity.this,msg.obj.toString(),Toast.LENGTH_LONG).show();try {client.subscribe(subTopic);} catch (MqttException e) {e.printStackTrace();throw new RuntimeException(e);}break;case 2:recvTxt.setText(msg.obj.toString());Toast.makeText(MainActivity.this,"Recv Data",Toast.LENGTH_LONG).show();break;case 3:recvTxt.setText(msg.obj.toString());Toast.makeText(MainActivity.this,msg.obj.toString(),Toast.LENGTH_LONG).show();break;case 4:recvTxt.setText(msg.obj.toString());Toast.makeText(MainActivity.this,msg.obj.toString(),Toast.LENGTH_LONG).show();break;case 5:Toast.makeText(MainActivity.this,"5",Toast.LENGTH_LONG).show();break;default:Toast.makeText(MainActivity.this,"default",Toast.LENGTH_LONG).show();break;}}}
}

ESP32

/*
//wifi連接
#include <WiFi.h>
const char* id="TP-LINK_8F3882";   //定義兩個字符串指針常量
const char* psw="123456789";
void setup() {Serial.begin(115200);WiFi.begin(id,psw);while(WiFi.status() != WL_CONNECTED){			//未連接上delay(500);Serial.println("wifi connecting...");}Serial.println("wifi connect ok!");				//連接上
}
void loop(){							//空循環}*/
/*Broker:
broker.emqx.io
TCP 端口:
1883
WebSocket 端口:
8083
SSL/TLS 端口:
8883
WebSocket Secure 端口:
8084
QUIC 端口:
14567
CA 證書文件:
broker.emqx.io-ca.crt
*/#include <WiFi.h>
#include <PubSubClient.h>// const char* ssid     = "Netcore_dsx";
// const char* password = "dsx54254";const char* ssid="TP-LINK_8F3882";   //定義兩個字符串指針常量
const char* password="123456789";//led
#define JDQ 2const char* MQTT_SERVER  = "broker.emqx.io";
const int   MQTT_PORT    = 1883;
const char* MQTT_USRNAME = "admin";
const char* MQTT_PASSWD  = "adminadmin";
const char* TOPIC = "dsx_esp8266";     //訂閱的主題  接收這個主題的消息
const char* CLIENT_ID    = "dsx_esp32_01";  //當前設備的clientid標志WiFiClient espClient;
PubSubClient  client(espClient);String send_msg="I am esp32";
String send_topic = "dsx_phone";   //往這個主題發送消息
void setup()
{Serial.begin(115200);delay(5000);Serial.println();Serial.println();Serial.print("Connecting to ");Serial.println(ssid);WiFi.begin(ssid, password);while (WiFi.status() != WL_CONNECTED) {delay(2500);Serial.print(".");}Serial.println("");Serial.println("WiFi connected");Serial.print("IP address: ");Serial.println(WiFi.localIP());pinMode(JDQ, OUTPUT);client.setServer(MQTT_SERVER, MQTT_PORT); //設定MQTT服務器與使用的端口,1883是默認的MQTT端口client.setCallback(callback);        //設定回調方式,當ESP8266收到訂閱消息時會調用此方法
}void reconnect() {while (!client.connected()) {Serial.println("Attempting MQTT connection...");if (client.connect(CLIENT_ID,MQTT_USRNAME,MQTT_PASSWD)) {Serial.println("Mqtt server connected success");// 連接成功時訂閱主題client.subscribe(TOPIC);Serial.println("Topic  dsx_esp32  subscribe success");pubmsg(send_topic,send_msg);} else {Serial.print("failed, rc=");Serial.print(client.state());Serial.println(" try again in 5 seconds");delay(5000);}}
}void callback(char* topic, byte* payload, unsigned int length) {Serial.print("Message arrived in topic: ");Serial.println(topic);Serial.print("Message: ");String message;for (int i = 0; i < length; i++) {message += (char) payload[i];  // Convert *byte to string}Serial.print(message);if (message == "on") {digitalWrite(JDQ, HIGH);  // Turn on the LEDpubmsg(send_topic, "LED ON");}if (message == "off") {digitalWrite(JDQ, LOW); // Turn off the LEDpubmsg(send_topic, "LED OFF");}Serial.println();Serial.println("-----------------------");
}// topicString   參數類似  "device/date" 
// messageString 參數類似  String realmsg="";void pubmsg( const String &topicString, const  String &messageString){char publishTopic[topicString.length() + 1];  strcpy(publishTopic, topicString.c_str());char publishMsg[messageString.length() + 1];   strcpy(publishMsg, messageString.c_str());// 實現ESP8266向主題發布信息if(client.publish(publishTopic, publishMsg)){Serial.print("Publish Topic:");Serial.println(publishTopic);Serial.print("Publish message:");Serial.println(publishMsg);   Serial.println("Send Success"); } else {Serial.println("Message Publish Failed."); }
}void loop()
{if (!client.connected()) {reconnect();}client.loop();
}

ESP8266

#include <ESP8266WiFi.h>
#include <PubSubClient.h>// 開發板上LED GPIO2 對應 D4  可以使用D4  也可以使用2    低電平點亮
#define LED 2// WiFi
const char *ssid = "Netcore_dsx"; // Enter your WiFi name
const char *password = "dsx54254";  // Enter WiFi password// MQTT Broker
const char *mqtt_broker = "broker.emqx.io";
const char *topic = "dsx_esp8266";
const char *mqtt_username = "emqx_dsx_esp8266";
const char *mqtt_password = "public_dsx_esp8266";
const int mqtt_port = 1883;
const char *send_topic = "dsx_phone";
bool ledState = false;WiFiClient espClient;
PubSubClient client(espClient);void setup() {// Set software serial baud to 115200;Serial.begin(115200);delay(1000); // Delay for stability// Connecting to a WiFi networkWiFi.begin(ssid, password);while (WiFi.status() != WL_CONNECTED) {delay(500);Serial.println("Connecting to WiFi...");}Serial.println("Connected to the WiFi network");// Setting LED pin as outputpinMode(LED, OUTPUT);digitalWrite(LED, HIGH);  // Turn off the LED initially// Connecting to an MQTT brokerclient.setServer(mqtt_broker, mqtt_port);client.setCallback(callback);while (!client.connected()) {String client_id = "esp8266-client-";client_id += String(WiFi.macAddress());Serial.printf("The client %s connects to the public MQTT broker\n", client_id.c_str());if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {Serial.println("Public EMQX MQTT broker connected");} else {Serial.print("Failed with state ");Serial.print(client.state());delay(2000);}}// Publish and subscribeclient.publish(send_topic, "hello phone");client.subscribe(topic);
}void callback(char *topic, byte *payload, unsigned int length) {Serial.print("Message arrived in topic: ");Serial.println(topic);Serial.print("Message: ");String message;for (int i = 0; i < length; i++) {message += (char) payload[i];  // Convert *byte to string}Serial.print(message);if (message == "on" && !ledState) {digitalWrite(LED, LOW);  // Turn on the LEDledState = true;client.publish(send_topic, "LED ON");}if (message == "off" && ledState) {digitalWrite(LED, HIGH); // Turn off the LEDledState = false;client.publish(send_topic, "LED OFF");}Serial.println();Serial.println("-----------------------");
}void loop() {client.loop();delay(100); // Delay for a short period in each loop iteration
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/163072.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/163072.shtml
英文地址,請注明出處:http://en.pswp.cn/news/163072.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Python dbm庫:利用鍵值對存儲數據

更多Python學習內容&#xff1a;ipengtao.com 大家好&#xff0c;我是濤哥&#xff0c;今天為大家分享 Python dbm庫&#xff1a;利用鍵值對存儲數據&#xff0c;文章6000字&#xff0c;閱讀大約20分鐘&#xff0c;大家enjoy~~ Python中的dbm模塊提供了一種輕量級的數據庫管理工…

【ARM 嵌入式 編譯系列 2.3 -- GCC 中指定 ARMv8-M 的 Thumb 指令集參數詳細介紹】

請閱讀【ARM GCC 編譯專欄導讀】 上篇文章:【ARM 嵌入式 編譯系列 2.2 – 如何在Makefile 中添加編譯時間 | 編譯作者| 編譯 git id】 下篇文章:【ARM 嵌入式 C 入門及漸進 3 – GCC attribute((weak)) 弱符號使用】 文章目錄 ARMv8-M 架構Thumb 指令集ARMv8-M 與 Thumb-mth…

call ,apply,bind 及異同點

目錄 1、call 2、apply 3、bind 4、三者異同 1、call call 函數調用 &#xff1a;1、讓函數執行 2、改變函數this指向 參數&#xff1a; 第一個參數是this指 向&#xff0c;第二個參數開始傳遞給函數的實參 函數名.call&#xff08;this指…

redis---主從復制及哨兵模式(高可用)

主從復制 主從復制&#xff1a;主從復制是redis實現高可用的基礎&#xff0c;哨兵模式和集群都是在主從復制的基礎之上實現高可用。 主從負責的工作原理 1、主節點&#xff08;master&#xff09; 從節點&#xff08;slave&#xff09;組成&#xff0c;數據復制是單向的&a…

VUE+element可以為空不為空時只能為(正整數和0)的驗證

rule{ 變量: [ { required: true, validator: validateparamPosition, trigger: blur }] } ??????? ??????? ??????? var validateparamPosition (rule, value, callback) > { if (!value) { //先判斷空可以過 ca…

【HarmonyOS】JSON格式化解析Map數據失敗

【關鍵字】 數據轉換、JSON.stringify、Object.fromEntries 【問題背景】 將數組轉換成Map對象&#xff0c;然后調用let str JSON.stringify(newMap)&#xff0c;將Map轉換成字符串&#xff0c;轉換出來的結果是{} 問題代碼&#xff1a; let data [{ key: where, value: …

python數據結構與算法-13_高級排序算法-快速排序

快速排序 快速排序名字可不是蓋的&#xff0c;很多程序語言標準庫實現的內置排序都有它的身影&#xff0c;我們就直奔主題吧。 和歸并排序一樣&#xff0c;快排也是一種分而治之(divide and conquer)的策略。歸并排序把數組遞歸成只有單個元素的數組&#xff0c;之后再不斷兩兩…

docker安裝mysql掛著目錄和mysql備份和恢復

第一&#xff0c;鏡像拉取&#xff0c;運行鏡像并掛載目錄&#xff0c;嘗試掛bin下&#xff0c;啟動不了&#xff0c;不知為啥 docker run --privilegedtrue -itd --namevmysql -p 3306:3306 -v /home/vmysql:/home/vmysql -e MYSQL_ROOT_PASSWORD123456 mysql&#xff08;圖…

Nancy (二)

最近做CS項目&#xff0c;一直在使用TCPSocket 做數據傳輸&#xff0c;不太爽&#xff0c;砸門可是多年BS的開發&#xff0c;這樣開發接口出去比較費勁&#xff0c;但是又不想用asp.net mvc webapi,要按照IIS&#xff0c;有些工控機的系統環境也是很尷尬的&#xff0c;那么也可…

用好說 AI 玩轉奧特曼表情包,居然還能和他們聊個天

你喜歡奧特曼嗎&#xff1f;你相信光嗎&#xff1f; 如果你已經追完了特攝劇、刷完了大電影、用濫了那幾個表情包&#xff0c;那不如來試試用 AI 給自己整點活兒新 “物料”。 不管是和奧特曼 “面對面” 聊天還是 “無中生有” 表情包&#xff0c;AI 都能做&#xff01; (※…

Python 使用SQLAlchemy數據庫模塊

SQLAlchemy 是用Python編程語言開發的一個開源項目&#xff0c;它提供了SQL工具包和ORM對象關系映射工具&#xff0c;使用MIT許可證發行&#xff0c;SQLAlchemy 提供高效和高性能的數據庫訪問&#xff0c;實現了完整的企業級持久模型。 ORM&#xff08;對象關系映射&#xff0…

MySQL For Windows的下載與安裝

教程https://www.bilibili.com/read/cv26499785/ windowse下載地址https://dev.mysql.com/get/Downloads/MySQLInstaller/mysql-installer-community-8.0.35.0.msi

代理模式 (Proxy Pattern)

定義&#xff1a; 代理模式&#xff08;Proxy Pattern&#xff09;是一種結構型設計模式&#xff0c;它通過提供一個代理&#xff08;或稱代表&#xff09;對象來控制對另一個對象的訪問。這種模式創建了一個代理對象&#xff0c;用來代表實際對象的功能&#xff0c;從而可以在…

spring boot 熱部署

相信小伙伴們在日常的開發中&#xff0c;調試代碼時&#xff0c;免不了經常修改代碼&#xff0c;這個時候&#xff0c;為了驗證效果&#xff0c;必須要重啟 Spring Boot 應用。 頻繁地重啟應用&#xff0c;導致開發效率降低&#xff0c;加班隨之而來。有沒有什么辦法&#xff0…

宏電股份受邀參加中國聯通戰新共創啟航大會,共筑產業生態,鏈通數智未來

11月21日&#xff0c;由中國聯通舉辦的主題為“共筑產業生態&#xff0c;鏈通數智未來”的網絡安全現代產業鏈共鏈行動計劃暨戰新共創啟航大會“5G工業互聯網”專題供需對接會在北京順利召開&#xff0c;宏電股份董事長左紹舟應邀出席活動。 會議現場&#xff0c;中國聯通雁飛…

Rust開發——數據對象的內存布局

枚舉與Sized 數據 一般數據類型的布局是其大小&#xff08;size&#xff09;、對齊方式&#xff08;align&#xff09;及其字段的相對偏移量。 1. 枚舉&#xff08;Enum&#xff09;的布局&#xff1a; 枚舉類型在內存中的布局通常是由編譯器來確定的。不同的編譯器可能有不…

centos7 系統keepalived 定時執行腳本

安裝keepalived yum install -y keepalived 修改配置文件 配置文件路徑 /etc/keepalived 配置文件內容 global_defs {router_id localhost.localdomain # 訪問到主機&#xff0c;本機的hostname&#xff0c;需要修改 }vrrp_script chk_http_port {script "/etc/kee…

INFLOW:用于檢測隱藏服務器的反向網絡流水印

文章信息 論文題目&#xff1a;INFLOW: Inverse Network Flow Watermarking for Detecting Hidden Servers 期刊&#xff08;會議&#xff09;&#xff1a;IEEE INFOCOM 2018 - IEEE Conference on Computer Communications 級別&#xff1a;CCF A 文章鏈接&#xff1a;https:…

Docker 安裝 Apache

目錄 拉取官方 Apache 鏡像 查看本地鏡像 列出正在運行的容器 運行 Apache 容器 創建一個 HTML 文件&#xff1a;index.html 訪問 Apache 拉取官方 Apache 鏡像 查找 Docker Hub 上的 httpd 鏡像。 可以通過 Tags 查看其他版本的 httpd&#xff0c;默認是最新版本 httpd…

人工智能學習階段有哪些?

人工智能學習階段有哪些? 人工智能是一個跨學科、跨領域的雜交學科&#xff0c;未來的趨勢來看,人工智能的出現使人們的生活變得更美好、更便捷&#xff0c;許多小伙伴想學習人工智能&#xff0c;其實看似人工智能比較雜多&#xff0c;無從下手&#xff0c;我們只要從以下7個階…