上一次讲了如何利用Nodejs接收MQTT服务器数据,现在想把Esp8266上面传感器的数据传输到MQTT服务器上面。 编译器是VS Code。
附注:Esp接收传感器数据,传输到MQTT服务器,然后Nodejs接收并保存到数据库。我们需要注意的是WIFI要供电脑和Esp使用,因为Esp和MQTT要保存在同一个局域网内,MQTT服务要启动,Nodejs程序开启之前,要开启MySQL,不然保存会报错。
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Arduino.h>
#include <U8g2lib.h>
#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif
// WIFI的账号
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;
void reconnect()
{
while (!client.connected())
{
Serial.print("Attempting MQTT connection...");
// client connect("id","username","password")
if (client.connect("arduinoClient","admin","password"))
{
Serial.println("connected");
}
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 < length; i++) {
arr[i] = (unsigned char)payload[i];
Serial.print(arr[i]);
}
// 在结果数组中加入'\0'作为结束符,否则结果数组结尾将乱码
arr[length] = '\0';
}
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服务器地址以及端口(地址是我本地IP地址,因为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) {
//Topic: hello
delay(5000);
client.publish("hello", str);
lastVal = val;
}
u8g2.sendBuffer();
delay(10);
}
关于pubsubclient库的使用:
https://pubsubclient.knolleary.net/api.html
https://github.com/knolleary/pubsubclient
MQTT协议中文版本:
https://legacy.gitbook.com/book/mcxiaoke/mqtt-cn/details
那我们如何接收MQTT服务器的数据,并传入数据库中呢?
/*连接MySQL*/
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
port : '3306',
database : 'test'
});
/*
connection.connect();
connection.end();
*/
/*接收MQTT协议数据*/
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('msg');
client.subscribe('hello');
client.subscribe('hello1');
client.subscribe('hello2');
// client.subscribe('world');
})
client.on('message', function (topic, message) {
switch (topic){
case "hello":
//获取当前时间(时间类型是Time 16:31:01)
var myDate = new Date();
var mytime = myDate.toLocaleTimeString();
var params1 = [mytime];
console.log("dataVal:",message.toString());
/*插入数据*/
var addSql = "INSERT INTO tvalues1(id,tdsvalue) VALUES(?,?)";
var addSqlParams = [message];
/*增*/
connection.query(addSql,[params1,addSqlParams],function (err,result) {
if(err){
console.log('[INSERT ERROR] - ',err.message);
return;
}
// console.log('-------------INSERT------------');
// console.log('INSERT ID:',result);
// console.log('-----------------------------\n\n');
})
break;
case "hello1":
console.log("dataVal:",message.toString())
/*插入数据*/
var addSql = "INSERT INTO tvalues1(id,tdsvalue) VALUES(0,?)";
var addSqlParams = [message];
/*增*/
connection.query(addSql,addSqlParams,function (err,result) {
if(err){
console.log('[INSERT ERROR] - ',err.message);
return;
}
// console.log('-------------INSERT------------');
// console.log('INSERT ID:',result);
// console.log('-----------------------------\n\n');
})
break;
case "hello2":
console.log("dataVal:",message.toString())
/*插入数据*/
var addSql = "INSERT INTO tvalues2(id,tdsvalue) VALUES(0,?)";
var addSqlParams = [message];
/*增*/
connection.query(addSql,addSqlParams,function (err,result) {
if(err){
console.log('[INSERT ERROR] - ',err.message);
return;
}
// console.log('-------------INSERT------------');
// console.log('INSERT ID:',result);
// console.log('-----------------------------\n\n');
})
break;
}
})
其中hello、hello1、hello2等是针对MQTT订阅的不同传感器传输的数据,如下面:
client.publish("hello",str);
//client.publish("hello1",str);
//client.publish("hello2",str);