没有实际接触过iOT的流程,应该实际使用比这个接口返回要复杂,只是演示~希望能参与实际的接口接入,而不是只展示个假数据。
启动RabbitQ
使用的是3.8.5 启动命令
RabbitMQ Service - start
RabbitMQ Command Prompt
rabbitmqctl
start_app
rabbitmq
-plugins enable
rabbitmq_management
rabbitmq-plugins enable rabbitmq_web_mqtt
rabbitmq-plugins enable rabbitmq_mqtt
访问
http://localhost:15672
账号:guest 密码:guest
查看命令:rabbitmq-plugins list
1883端口已开
MQTT模拟收发
模拟IoT设备发送
import mqtt from 'mqtt'
const options = {
username:"guest",
password:"guest"
}
var client = mqtt.connect("mqtt://localhost:1883", options);
function sendTemperature() {
// 生成一个0到40之间的随机温度值
const temperature = Math.floor(Math.random() * 40);
const now = new Date();
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();
const ioTdata = `Time:${hours}:${minutes}:${seconds},temperature:${temperature}`
console.log(`Sending iOTData: ${ioTdata}`);
client.publish('sensor/temperature', ioTdata);
}
// 连接成功
client.on('connect', function () {
console.log('Connected');
setInterval(sendTemperature, 1000);
});
// 连接失败
client.on('error', function (err) {
console.log('Connection error: ', err);
});
模拟存储设备接收
import mqtt from 'mqtt'
import * as fs from 'fs'
const options = {
username:"guest",
password:"guest"
}
var client = mqtt.connect("mqtt://localhost:1883", options);
// 连接成功
client.on('connect', function () {
console.log('Connected');
// 订阅主题
client.subscribe('sensor/temperature', function (err) {
if (!err) {
console.log('Subscribed');
}
});
});
// 接收消息
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString());
recordTemperature(message)
//client.end(); // 接收完消息后断开连接
});
// 连接失败
client.on('error', function (err) {
console.log('Connection error: ', err);
});
// 连接关闭
// client.on('close', function () {
// console.log('Connection closed');
// });
function recordTemperature(data){
fs.appendFile("./record.txt",data+"\n",(err)=>{
if (err) {
console.error(err);
return;
}
})
}
后端起服务读取本地信息
import express from 'express'
import * as fs from 'fs'
import cors from 'cors'
const app = express();
const port = 5000;
app.use(cors());
app.get('/v1/iotdataDemo', (req, res) => {
let data="";
try {
data = fs.readFileSync('./record.txt', 'utf8');
} catch (err) {
console.error(err);
}
if(data.length === 0) return;
res.json({ iotData: data.split("\n") });
});
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});