NB-IOT接入阿里云平台MQTT协议实现数据传输代码
时间: 2023-11-23 17:07:16 浏览: 242
以下是基于Arduino平台,使用Arduino IDE编写的NB-IoT接入阿里云平台MQTT协议实现数据传输的示例代码。在使用前需要先在阿里云平台创建设备和Topic,并且获取对应的设备信息和证书。
```C++
#include <SoftwareSerial.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <DFRobot_SIM808.h>
//定义NB-IoT模块相关参数
#define PIN_TX 7
#define PIN_RX 8
#define BAUDRATE 9600
//定义DS18B20温度传感器相关参数
#define ONE_WIRE_BUS 2
#define TEMPERATURE_PRECISION 9
//定义阿里云MQTT平台相关参数
#define MQTT_SERVER "xxx.mqtt.aliyuncs.com" //MQTT服务器地址
#define MQTT_PORT 1883 //MQTT服务器端口
#define MQTT_CLIENT_ID "GID_xxxxxxxxxxxxxx" //客户端ID
#define MQTT_USERNAME "xxxxxxxxxxxxx" //MQTT用户名
#define MQTT_PASSWORD "xxxxxxxxxxxxx" //MQTT密码
#define MQTT_TOPIC "/xxxxxxxxxxxxx/xxxxxxxxxxxxx" //MQTT Topic
SoftwareSerial mySerial(PIN_RX, PIN_TX);
DFRobot_SIM808 sim808(&mySerial);//创建NB-IoT模块对象
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
WiFiClient wifiClient;
PubSubClient mqttClient(MQTT_SERVER, MQTT_PORT, wifiClient);
void setup() {
Serial.begin(9600);
mySerial.begin(BAUDRATE);
while(!sim808.init());//等待模块初始化完成
delay(2000);
Serial.println("SIM808 init success!");
sensors.begin();
}
void loop() {
sim808.checkPowerUp();//检查模块是否开机
if (sim808.isNetworkRegistered()) {
Serial.println("Network is registered.");
if (sim808.isGprsActived()) {
Serial.println("GPRS is actived.");
if (!mqttClient.connected()) {
Serial.println("MQTT client is not connected.");
connectMqttServer();
}
mqttClient.loop();
float temperature = readTemperature();
publishMqttMessage(temperature);
} else {
Serial.println("GPRS is not actived, trying to activate...");
sim808.activeGprs("CMNET");//激活GPRS
}
} else {
Serial.println("Network is not registered, trying to register...");
sim808.waitForNetworkRegistered();//等待网络注册
}
}
float readTemperature() {
sensors.requestTemperatures();
float temperature = sensors.getTempCByIndex(0);
return temperature;
}
void connectMqttServer() {
Serial.println("Connecting to MQTT server...");
if (mqttClient.connect(MQTT_CLIENT_ID, MQTT_USERNAME, MQTT_PASSWORD)) {
Serial.println("MQTT server connected.");
mqttClient.subscribe(MQTT_TOPIC);//订阅MQTT Topic
} else {
Serial.print("Failed to connect MQTT server, rc=");
Serial.println(mqttClient.state());
}
}
void publishMqttMessage(float temperature) {
StaticJsonDocument<200> jsonDoc;
jsonDoc["temperature"] = temperature;
char message[200];
serializeJson(jsonDoc, message, sizeof(message));
mqttClient.publish(MQTT_TOPIC, message);//发布MQTT消息
}
```
此代码实现了以下功能:
1. 连接NB-IoT模块和DS18B20温度传感器;
2. 检查NB-IoT网络状态;
3. 激活GPRS连接;
4. 连接阿里云MQTT平台;
5. 订阅指定的MQTT Topic;
6. 读取DS18B20传感器数据;
7. 将温度数据以JSON格式发布到MQTT Topic。
注意:由于NB-IoT网络和阿里云MQTT平台的连接较为复杂,上述代码仅供参考,具体实现需要根据实际情况进行调整。
阅读全文