ESP32通过MQTT连接阿里云平台实现消息发布与订阅

文章目录

前言

一、准备工作

二、阿里云平台配置

三、代码实现

总结


前言

本文将介绍如何使用ESP32开发板通过MQTT协议连接阿里云物联网平台,并实现消息的发布与订阅功能。我们将使用Arduino IDE进行开发,并借助PubSubClient库实现MQTT通信。

一、准备工作

  • ESP32开发板
  • Arduino IDE
  • 阿里云物联网平台账号
  • PubSubClient库

二、阿里云平台配置

  1. 登录阿里云物联网平台

  2. 创建产品与设备,获取设备三元组(ProductKey、DeviceName、DeviceSecret)

  3. 配置Topic,例如:

  • 发布Topic: /a1xxxxxx/${deviceName}/user/update
  • 订阅Topic: /a1xxxxxx/${deviceName}/user/get

三、代码实现

复制代码
#include <WiFi.h>
#include <PubSubClient.h>

// WiFi配置
const char* ssid = "your_wifi_ssid";
const char* password = "your_wifi_password";

// 阿里云MQTT配置
const char* mqtt_server = "iot-xxxxxx.mqtt.aliyuncs.com";
const int mqtt_port = 1883;
const char* mqtt_clientId = "your_client_id";
const char* mqtt_username = "your_device_name&your_product_key";
const char* mqtt_password = "your_device_secret";

WiFiClient espClient;
PubSubClient client(espClient);

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 callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect(mqtt_clientId, mqtt_username, mqtt_password)) {
      Serial.println("connected");
      client.subscribe("/a1xxxxxx/${deviceName}/user/get");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  // 发布消息示例
  static unsigned long lastMsg = 0;
  if (millis() - lastMsg > 5000) {
    lastMsg = millis();
    String msg = "Hello from ESP32";
    client.publish("/a1xxxxxx/${deviceName}/user/update", msg.c_str());
    Serial.println("Message published");
  }
}

其中,setup_wifi()用于连接WiFi网络,callback()用于处理接收到的MQTT消息,reconnect()用于处理MQTT连接与重连。


总结

通过本文,能够成功实现了ESP32与阿里云物联网平台的MQTT通信。

相关推荐
xhbaitxl7 小时前
算法学习day27-贪心算法
学习·算法·贪心算法
txinyu的博客7 小时前
用户态与内核态
linux·运维·服务器
yongui478347 小时前
异构网络垂直切换算法MATLAB仿真实现
网络·算法·matlab
半路_出家ren7 小时前
5.RSA和AES加密(python)
服务器·网络·python·https·aes·rsa·加密算法
Sarvartha7 小时前
RAG学习笔记
人工智能·学习·飞书
马猴烧酒.7 小时前
智能协图云图库学习笔记day6-主流图片优化技术
笔记·学习
michael_ouyang7 小时前
IM 消息收发流程方案选型
前端·websocket·网络协议·typescript·electron
上海云盾-小余7 小时前
WAF性能优化:如何平衡安全防护与网站访问速度?
网络·安全·性能优化
北京耐用通信8 小时前
耐达讯自动化Profibus光纤中继模块实现冶金车间长距离抗干扰通信
人工智能·物联网·网络协议·自动化·信息与通信
Python_Study20258 小时前
制造业数字化转型中的数据采集系统:技术挑战、架构方案与实施路径
大数据·网络·数据结构·人工智能·架构