Arduino中使用PubSubClient对接阿里云物联网平台

简介: Arduino中使用PubSubClient对接阿里云物联网平台

最近在捣鼓一个esp-12f的板子,看到可以用Arduino搭建开发环境,就尝试弄了下。在Arduino菜单工具-》管理库,添加esp8266和pubsubclient库。pubsubclient库的github地址是:

https://github.com/knolleary/pubsubclient,使用例子mqtt_esp8266,修改了一些参数连接阿里云物联网平台,代码如下:

/*
 Basic ESP8266 MQTT example
 This sketch demonstrates the capabilities of the pubsub library in combination
 with the ESP8266 board/library.
 It connects to an MQTT server then:
  - publishes "hello world" to the topic "outTopic" every two seconds
  - subscribes to the topic "inTopic", printing out any messages
    it receives. NB - it assumes the received payloads are strings not binary
  - If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
    else switch it off
 It will reconnect to the server if the connection is lost using a blocking
 reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
 achieve the same result without blocking the main loop.
 To install the ESP8266 board, (using Arduino 1.6.4+):
  - Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":
       http://arduino.esp8266.com/stable/package_esp8266com_index.json
  - Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
  - Select your ESP8266 in "Tools -> Board"
*/
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char* ssid = "***";
const char* password = "***";
const char* mqtt_server = "productkey.iot-as-mqtt.cn-shanghai.aliyuncs.com";
const int mqtt_port = 1883;
const char *mqtt_user = "devicename&productkey";
const char *mqtt_pass = "***";
const char *mqtt_clientId = "productkey.devicename|securemode=3,signmethod=hmacsha256,timestamp=1673499136899|"; 
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE  (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  randomSeed(micros());
  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();
  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    //digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is active low on the ESP-01)
  } else {
    //digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  }
}
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    //String clientId = "ESP8266Client-";
    //clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(mqtt_clientId, mqtt_user, mqtt_pass)) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("/productkey/devicename/user/update", "hello world");
      // ... and resubscribe
      client.subscribe("/productkey/devicename/user/get");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
void setup() {
  //pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);
}
void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  unsigned long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("/productkey/devicename/user/update", msg);
  }
}

一开始报错,报错信息:failed, rc=-1  try again in 5 seconds",看了下源码-1的定义是这个:

#defineMQTT_DISCONNECTED           -1

然后大体浏览了下源码,猜测可能是MQTT_MAX_PACKET_SIZE的值太小导致,修改为:

#define MQTT_MAX_PACKET_SIZE 256

修改源码保存后,再次运行程序,可以正常连接到平台。


相关实践学习
阿里云AIoT物联网开发实战
本课程将由物联网专家带你熟悉阿里云AIoT物联网领域全套云产品,7天轻松搭建基于Arduino的端到端物联网场景应用。 开始学习前,请先开通下方两个云产品,让学习更流畅: IoT物联网平台:https://iot.console.aliyun.com/ LinkWAN物联网络管理平台:https://linkwan.console.aliyun.com/service-open
目录
相关文章
|
3月前
|
消息中间件 安全 物联网
海量接入、毫秒响应:易易互联携手阿里云构筑高可用物联网消息中枢
面对换电生态高速发展的通信挑战,易易互联通过采用阿里云 MQTT + RocketMQ 的融合解决方案,成功构建了“海量接入、实时响应、弹性处理、安全可信”的物联网通信底座。该架构不仅显著提升了系统稳定性与可扩展性,更保障了高并发场景下的业务连续性,为实现“让换电成为营运补能第一选择”的战略目标提供了坚实的技术支撑。
221 37
|
7月前
|
物联网
(手把手)在华为云、阿里云搭建自己的物联网MQTT消息服务器,免费IOT平台
本文介绍如何在阿里云搭建自己的物联网MQTT消息服务器,并使用 “MQTT客户端调试工具”模拟MQTT设备,接入平台进行消息收发。
2583 42
|
9月前
|
存储 监控 安全
工业物联网关应用:PLC数据通过智能网关上传阿里云实战
本文介绍如何使用智能网关将工厂PLC数据传输至阿里云平台,适合中小企业远程监控设备状态。硬件准备包括三菱FX3U PLC、4G智能网关和24V电源。接线步骤涵盖PLC编程口与网关连接、运行状态检测及天线电源接入。配置过程涉及通讯参数、阿里云对接和数据点映射。PLC程序关键点包括数据上传触发和温度值处理。阿里云平台操作包含实时数据查看、数据可视化和规则引擎设置。最后提供常见故障排查表和安全建议,确保系统稳定运行。
826 1
|
10月前
|
物联网 数据挖掘 BI
基于阿里云物联网平台(IoT)的智能家居系统开发与部署
随着物联网技术的发展,智能家居成为提升生活品质的重要方向。阿里云物联网平台提供设备接入、数据管理及应用开发能力,支持亿级设备接入、高效数据管理和灵活应用开发,确保系统安全。本文通过实战案例展示如何基于该平台构建智能家居系统,涵盖设备接入、远程控制、场景联动与数据分析等功能,助力企业快速部署智能家居解决方案。
|
存储 边缘计算 物联网
阿里云物联网平台:推动万物互联的智能化解决方案
随着物联网技术的快速发展,阿里云物联网平台为企业提供了一体化的解决方案,包括设备接入、数据管理和智能应用等核心功能。平台支持海量设备接入、实时数据采集与存储、边缘计算,并具备大规模设备管理、高安全性和开放生态等优势。广泛应用于智能制造、智慧城市和智能家居等领域,助力企业实现数字化转型。
1498 5
|
监控 安全 物联网
物联网:如何对接物联网卡的管理平台
对接物联网平台的API通常涉及几个关键步骤,这些步骤帮助你有效地与平台交互,实现设备数据的收集、处理、分析及控制等功能。以下是一个通用的对接流程:
|
存储 运维 监控
阿里云物联网平台的优势
【7月更文挑战第19天】阿里云物联网平台的优势
491 1
|
9月前
|
传感器 人工智能 物联网
健康监测设备的技术革命:AI+物联网如何让你随时掌握健康数据?
健康监测设备的技术革命:AI+物联网如何让你随时掌握健康数据?
1150 19
|
存储 安全 物联网
政府在推动物联网技术标准和规范的统一方面可以发挥哪些作用?
政府在推动物联网技术标准和规范的统一方面可以发挥哪些作用?
440 60
|
安全 物联网 物联网安全
制定统一的物联网技术标准和规范的难点有哪些?
制定统一的物联网技术标准和规范的难点有哪些?
483 58

相关产品

  • 物联网平台