oneNet MQTT程序

参考别人的程序,自己还没测试

#include <Arduino.h>
#include <WiFi.h>
#include <PubSubClient.h>
//#include <ArduinoJson.h>
#include "DHT.h"

#define DHTPIN 5      // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT 11
#define BUILTIN_LED 21

// Update these with values suitable for your network.

const char *ssid = "YourWifiSSID";//你的WiFi SSID
const char *password = "WiFIPassword";//WiFi密码
const char *mqtt_server = "183.230.40.96";//OneNet MQTT接入服务器IP,按开发文档说明设置

const char *clientid = "设备名称";//OneNet注册设备的“设备名称”
const char *userid = "产品ID";//OneNet 注册的MQTT产品的“产品ID”
char outTopic[] = "$sys/产品ID/设备名称/dp/post/json";//数据上传的Topic,格式为“$sys/userid/clientid/dp/post/json”
char inTopic[] = "$sys/产品ID/设备名称/dp/post/json/+";//数据返回的Topic,格式为“$sys/userid/clientid/dp/post/json/+”
char cmdTopic[] = "$sys/产品ID/设备名称/cmd/#";//接收平台命令的TOPIC,格式为“$sys/userid/clientid/cmd/#”
int switch0 = 0;//开关状态

DHT dht(DHTPIN, DHTTYPE);
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
//数据上报格式模板,按网上例程的不成功,只能按下列格式,有Temperatrue、Humidity、switch0三个数据点
char dataTemplete[] = "{\"id\":1,\"dp\":{\"Temperatrue\":[{\"v\":%5.1f}],\"Humidity\":[{\"v\":%5.1f}],\"switch0\":[{\"v\":%d}]}}";
char msgJson[100];//上传的数据

void setup_wifi()
{
    delay(10);
    // We start by connecting to a WiFi network
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);
    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());
    //  digitalWrite(BUILTIN_LED, HIGH);
}

//收到订阅Topic信息的回调处理
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();

    // 平台发来命令“1”时开灯
    if ((char)payload[0] == '1')
    {
        switch0 = 1;
        //digitalWrite(BUILTIN_LED, HIGH);
    }
    else
    {
        switch0 = 0;
        //digitalWrite(BUILTIN_LED, LOW);
    }
    digitalWrite(BUILTIN_LED, switch0);
}

void reconnect()
{
    // Loop until we're reconnected
    while (!client.connected())
    {
        Serial.print("Attempting MQTT connection...");
        // Attempt to connect
        if (client.connect(clientid, userid, "token.exe算出来的密码"))
        { //One net 的密码不是 APIKey,要用OneNet提供的“token.exe”计算得到,计算时res为:products/userid/devices/clientid、
        //key为:注册设备的key、et为设个截止日期(超过截止日期后密码失效),到网上用转换工具转换的Unix时间
            Serial.println("connected");
            //订阅inTop的消息,上报数据后平台自动发来的
            //      client.unsubscribe (inTopic);
            //订阅平台发来命令消息
            client.subscribe(cmdTopic);
        }
        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, where do it esp32 get gpio21 as led
    Serial.begin(9600);
    setup_wifi();
    client.setServer(mqtt_server, 1883); //按OneNet开发文档设置端口为1883
    client.setCallback(callback);
    dht.begin();
}

void loop()
{

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

    long now = millis();
    if (now - lastMsg > 2000)
    {
        // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
        float h = dht.readHumidity();
        // Read temperature as Celsius (the default)
        float t = dht.readTemperature();

        lastMsg = now;
        sprintf(msgJson, dataTemplete, t, h, switch0);//按模板格式化上传数据到msgJson
        Serial.print("Publish message: ");
        Serial.println(msgJson);
        client.publish(outTopic, msgJson);//上传
        //delay(5000);
    }
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值