Nodejs利用MQTT把数据传输到Esp8266

前两篇文章实现了Nodejs接收MQTT服务器数据,和Esp8266传感器数据传输到MQTT服务器,现在是想通过Nodejs把数据传输到Esp8266上面,从而可以控制Esp8266传感器数据采集的时间间隔。

主要还是PubSubClient库的subscribe和publish的使用。还有npm里面mqtt的使用。

参考文章:https://github.com/knolleary/pubsubclient/blob/master/examples/mqtt_esp8266/mqtt_esp8266.ino
https://www.npmjs.com/package/mqtt

Nodejs端使用的代码:

/*接收MQTT协议数据(传输数据主要是设置publish的参数)*/
var mqtt = require('mqtt')
var fs = require('fs')

var client  = mqtt.connect('mqtt://127.0.0.1:61613',{username:"admin",password:"password"})

client.on('connect',function () {
    client.subscribe('world');
    client.publish('world','5000');
})

client.on('message', function (topic, message) {

  console.log(typeof message);
  console.log(message.toString());
  client.end();

})

Esp8266端代码:

// 主要是在回调函数callback()内对数据进行接收
#include 
#include 


#include 
#include 

#ifdef U8X8_HAVE_HW_SPI
#include 
#endif
#ifdef U8X8_HAVE_HW_I2C
#include 
#endif

const char *ssid = "smart";
const char *password = "19940508";

WiFiClient espClient;
PubSubClient client(espClient);


U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/D3, /* data=*/D2, /* reset=*/U8X8_PIN_NONE);

int lastVal = 0;

int ordernum = 1000;
// String offcommand ;

void reconnect()
{
  while (!client.connected())
  {
    Serial.print("Attempting MQTT connection...");
    // client connect("id","username","password")
    if (client.connect("arduinoClient","admin","password"))
    {
      Serial.println("connected");

       // 接收Topic:world
      client.subscribe("world");
    }
    else
    {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // 设置5s 尝试重连
      delay(5000);
    }
  }
}


void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  char arr[length];
  for (int i = 0; i < (int)length; i++) {
    arr[i] = (unsigned char)payload[i];
    // Serial.print(arr[i]);
  }
  // 在结果数组中加入'\0'作为结束符,否则结果数组结尾将乱码
  arr[length] = '\0';
  // Serial.println(arr);

  //char类型转换成int
  ordernum = atoi(arr);
  Serial.println(ordernum);

}


void setup()
{
  Serial.begin(9600);
  u8g2.begin();

  delay(10);
  Serial.println();
  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());
  // 设置mqtt服务器地址以及端口
  client.setServer("192.168.43.65", 61613);
  client.setCallback(callback);

  pinMode(A0,INPUT);
}


void loop()
{

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

  int val = analogRead(A0);
  char str [10];
  itoa(val, str, 10);
  u8g2.clearBuffer();
  u8g2.setFont(u8g2_font_ncenB08_tr);
  u8g2.drawStr(0, 30, str);
  if (val != lastVal) {
    // 时间间隔ordernum
    // Topic: hello
    delay(ordernum);
    client.publish("hello", str);
    lastVal = val;
  }

  u8g2.sendBuffer();
  delay(10);
}

大致代码就是这样了。

你可能感兴趣的:(Arduino)