本帖最后由 3472076282 于 2024-11-26 09:42 编辑
ESP32 端代码首先,确保你已经安装了所需的库,例如 PubSubClient 和 WiFi。 #include <WiFi.h> #include <PubSubClient.h> // WiFi credentials const char* ssid = "your_SSID"; const char* password = "your_PASSWORD"; // MQTT Broker const char* mqtt_server = "broker.hivemq.com"; WiFiClient espClient; PubSubClient client(espClient); void setup() { Serial.begin(115200); setup_wifi(); client.setServer(mqtt_server, 1883); } void setup_wifi() { delay(10); Serial.println(); 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.println("IP address: "); Serial.println(WiFi.localIP()); } void reconnect() { while (!client.connected()) { Serial.print("Attempting MQTT connection..."); if (client.connect("ESP32Client")) { Serial.println("connected"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); delay(5000); } } } void loop() { if (!client.connected()) { reconnect(); } client.loop(); } Android 端代码在Android端,你可以使用Paho MQTT库来连接到MQTT Broker并发送/接收消息。以下是一个基本的示例: 1. 添加依赖项到你的 build.gradle 文件: dependencies { implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5' implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1' } 2. 创建一个服务来处理MQTT连接: import android.app.Service; import android.content.Intent; import android.os.IBinder; import org.eclipse.paho.android.service.MqttAndroidClient; import org.eclipse.paho.client.mqttv3.IMqttActionListener; import org.eclipse.paho.client.mqttv3.IMqttToken; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttMessage; public class MqttService extends Service { private static final String MQTT_BROKER_URL = "tcp://broker.hivemq.com:1883"; private static final String CLIENT_ID = "AndroidClient"; private MqttAndroidClient mqttAndroidClient; @Override public void onCreate() { super.onCreate(); mqttAndroidClient = new MqttAndroidClient(this, MQTT_BROKER_URL, CLIENT_ID); mqttAndroidClient.setCallback(new MqttCallback() { @Override public void connectionLost(Throwable cause) { // handle connection loss } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { // handle incoming message } @Override public void deliveryComplete(IMqttDeliveryToken token) { // handle message delivery complete } }); } @Override public int onStartCommand(Intent intent, int flags, int startId) { connectToMqttBroker(); return START_STICKY; } private void connectToMqttBroker() { try { mqttAndroidClient.connect(null, new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { // subscribe to a topic or publish a message } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { // handle failure to connect } }); } catch (Exception e) { e.printStackTrace(); } } @Override public IBinder onBind(Intent intent) { return null; } } 3. 启动服务: Intent serviceIntent = new Intent(this, MqttService.class); startService(serviceIntent); 4. 发布或订阅消息: // To publish a message String topic = "test/topic"; String message = "Hello from Android"; try { mqttAndroidClient.publish(topic, message.getBytes(), 0, false); } catch (Exception e) { e.printStackTrace(); } // To subscribe to a topic String topic = "test/topic"; try { mqttAndroidClient.subscribe(topic, 0); } catch (Exception e) { e.printStackTrace(); } 图片传输示例假设你要传输一张图片,可以将图片转换为字节数组并通过MQTT发送。以下是一个简单的例子: ESP32 端接收图片数据:void callback(char* topic, byte* payload, unsigned int length) { // Assuming the payload is the image data in bytes for (int i = 0; i < length; i++) { Serial.print((char)payload); } Serial.println(); } Android 端发送图片数据:Bitmap bitmap = ... // your bitmap image ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); // bmp is your Bitmap instance byte[] bytes = baos.toByteArray(); String base64Image = Base64.encodeToString(bytes, Base64.DEFAULT); try { mqttAndroidClient.publish("image/topic", base64Image.getBytes(), 0, false); } catch (Exception e) { e.printStackTrace(); } 以上代码展示了如何在ESP32和Android之间通过MQTT进行图片传输的基本方法。根据你的具体需求,你可能需要进一步优化和调整代码。 |