ESP8266与阿里云物联网平台连接

前言

最近折腾项目,需要用到ESP8266模块对接阿里云物联网平台,网上感觉十分完善的教程少了一点点,比较折腾我哈哈哈,所以打算自己写一篇。

材料准备

1、ESP8266 WiFi模块 + 数据线

网上随便买一个就好,十块钱左右一个。我购买的是CH340C芯片的。

2、Arduino IDE

3、阿里云平台

ESP8266

 1、连接电脑

        好像有些网上购买的不需要固件烧录。但是我购买的这个要,不然识别不了AT指令。首先使用一根数据线进行ESP8266模块与电脑进行连接。有些模块是Micro口(老式安卓口),有些是TypeC口,根据自己的模块,使用对应的数据线。

        连接好后,检查电脑有没有声音响起,或者可以前往设备管理器查看:

        通过插拔数据线,观察端口是否缺少,如果没有缺少,根据我的经历来说,有如下两种可能(可能还有别的特殊情况,但是暂时没遇到):

  • 驱动没安装
  • 你使用的数据线不支持数据传输 

        对于第一种,可以前往去安装对应芯片的驱动,例如CH340C芯片安装CH340驱动,CP2102芯片安装CP210X驱动。可百度搜索一下。

        对于第二种,换一根数据线即可。

2、固件烧录

        NodeMcu-AT-1.zip - lingshunlab 的分享 (u062.com)

        通过上述连接,可以下载固件烧录软件。下载解压后,在此目录下双击启动:

         选择第一个:

        点击如图:

        找到如下路径的文件进行打开:

         随后按照我的配置勾选,同时在右下角选择自己的模块所占的端口,比如是COM1(端口可在设备管理器查询),波特率选择115200。有些模块背面写的9600默认,忽视它。然后点击START,等待一段漫长的时间。

        等到FINISH的出现,说明固态烧写完成。可以来使用串口助手验证。我这里使用的微软商店的串口调试助手,UI较为简介,界面不像老古董。哈哈哈。

        界面如图所示:

         选择ESP8266对应的端口号,比如我这里是COM7。波特率选择115200.无误之后选择打开。在下方输入框中输入:AT(换行!注意一定要换行),点击右方发送,显示OK就是烧录成功:

阿里云平台

1、注册、登录

        阿里云-计算,为了无法计算的价值 (aliyun.com)

        网站如上,进入后右上角可以注册或者登录。我就不教了。

2、开通物联网平台

        新用户一般是没开通过的,如图点击,一般会让你开通。你就选择开通就好,免费的

3、 创建产品、设备

 

         产品添加好了,接下来添加设备:

        刚添加的设备一般是未激活状态,需要激活才能使用,激活也就是连接MQTT。

 Arduino IDE

1、软件下载、安装

        网上自行下载,这里就不提供了。

2、获取PubSubClient库

        https://github.com/knolleary/pubsubclient

        仓库地址如上,下载src文件下的两个文件,放入自己的工程文件夹中:

3、打开IDE

        在刚下载的两个文件的文件夹中,新建一个.ino文件,用Arduino IDE打开,随后输入:

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include "PubSubClient.h"
#include <Crypto.h>
#include <Arduino.h>
// Update these with values suitable for your network.

using experimental::crypto::SHA256;

// 实例化一个对象 wifiMulti
ESP8266WiFiMulti wifiMulti;

WiFiClient espClient;

PubSubClient client(espClient);

void connetMqtt();
String signHmacSha256(String deviceId, String productKey, String deviceName, String deviceSecret, uint64_t timestamp);
void callback(char *topic, byte *payload, unsigned int length);

const String productKey = "***";                        //替换
const String deviceName = "***";               //替换
const String deviceSecret = "***"; //替换
const String subTopic = "/" + productKey + "/" + deviceName + "/user/get";
const String pubTopic = "/" + productKey + "/" + deviceName + "/user/update";
const String regionId = "cn-shanghai"; //替换自己的区域id
const String serverUrl = productKey + ".iot-as-mqtt." + regionId + ".aliyuncs.com";
const int serverPort = 1883;

const char wifiName[] = "***";//替换
const char wifiPassword[] = "***";//替换

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(115200);

  wifiMulti.addAP(wifiName, wifiPassword);
  Serial.println("");
  Serial.println("start connecting wifi...");

  while (wifiMulti.run() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(1000);
  }
  Serial.println("============connect wifi success============");
  Serial.print("WiFi:");
  Serial.println(WiFi.SSID()); 
  Serial.print("localIP:");
  Serial.println(WiFi.localIP()); 

  connetMqtt();
}

void connetMqtt()
{
  Serial.println("start connect mqtt ....");
  client.setKeepAlive(60); //注意:PubSubClient库的默认keepalive是15s,而官方要求(30~1200s)最小30s,否则会拒绝连接
  client.setServer(serverUrl.c_str(), serverPort);

  String deviceId = String(ESP.getChipId()); //设备芯片唯一序列号
  uint64_t timestamp = micros64();

  String clientId = deviceId + "|securemode=3,signmethod=hmacsha256,timestamp=" + timestamp + "|";
  String password = signHmacSha256(deviceId, productKey, deviceName, deviceSecret, timestamp);
  String username = deviceName + "&" + productKey;
  Serial.print("clientId:");
  Serial.println(clientId);
  Serial.print("username:");
  Serial.println(username);
  Serial.print("password:");
  Serial.println(password);

  client.connect(clientId.c_str(), username.c_str(), password.c_str());

  while (!client.connected())
  {
    /* code */
    delay(2000);
    client.connect(clientId.c_str(), username.c_str(), password.c_str());
    Serial.println("try connect mqtt...");
  }
  Serial.println("ok, mqtt connected!");
  client.subscribe(subTopic.c_str());
  client.setCallback(callback);
}

String signHmacSha256(String deviceId, String productKey, String deviceName, String deviceSecret, uint64_t timestamp)
{
  const char *key = deviceSecret.c_str();
  String data = "clientId" + deviceId + "deviceName" + deviceName + "productKey" + productKey + "timestamp" + timestamp;
  Serial.print("sha256:");
  Serial.println(data);
  return SHA256::hmac(data, key, strlen(key), SHA256::NATURAL_LENGTH);
}

void callback(char *topic, byte *payload, unsigned int length)
{
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  payload[length] = '\0';
  String message = String((char *)payload);
  Serial.println(message);
}

void loop()
{
  // put your main code here, to run repeatedly:
  if (client.connected())
  {
    client.loop(); //心跳以及消息回调等
  }
}

        以上所需信息,都可以在阿里云物联网控制台查找:

        随后,文件——首选项——其他开发板管理地址:填写如下:

http://arduino.esp8266.com/stable/package_esp8266com_index.json

        

        在开发板管理器中,搜索ESP8266,下载如图所示的开发板:

        这个下载巨巨巨巨巨慢,大约要一两个小时。

        下载完后,在工具——开发板——esp8266——Generic ESP8266 Modules。选择好对应的串口,然后点击下方按钮即可编译运行(编译运行可能会提示要下载什么东西,下载就好):

4、运行

        正确运行会显示以下信息:

        在设备列表,也能看见在线。        

验证

        代码里写的默认是订阅: "/" + productKey + "/" + deviceName + "/user/get"

        我们可以在阿里云物联网控制台,点击我们的设备,在Topic列表中,找到这个主题,选择发布信息:

                 

         发布后,我们打开IDE:发现已经收到!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值