Files
remotedevinfoshow/server/comman/mqqtclinet.js
2024-07-19 13:58:44 +08:00

158 lines
3.6 KiB
JavaScript

const mqtt = require('mqtt');
const db=require("./db")
// db.resetpath("../db.sqlite3")
// 创建 MQTT 客户端实例
const client = mqtt.connect('mqtt://82.156.1.111:40000', {
clientId: 'web_collectorserver',
username: 'xin',
password: 'irishk'
});
client.subscribe("topic_who_is_here_back");
// 定义事件处理程序
client.on('connect', () => {
console.log('MQTT client connected');
client.subscribe('my/topic');
});
function converjsontokeyvalue(data)
{
let fields = [];
let fields1 = [];
let fields2 = [];
for (let key in data) {
// 如果值是字符串,需要用引号包裹
let value = typeof data[key] === 'string' ? `'${data[key]}'` : data[key];
fields1.push(key);
fields2.push( value);
}
fields.push(fields1.join(","))
fields.push(fields2.join(","))
return fields
}
function converjsontokeyequalvalue(data)
{
let fields = [];
for (let key in data) {
// 如果值是字符串,需要用引号包裹
let value = typeof data[key] === 'string' ? `'${data[key]}'` : data[key];
fields.push(key+"="+value);
}
return fields.join(",")
}
client.on('message', async (topic, message) => {
if (topic==="topic_who_is_here_back")
{
var data=JSON.parse(message.toString())
data.switch1=data.st[0];
data.switch2=data.st[1];
data.switch3=data.st[2];
data.switch4=data.st[3];
if (data.switch1===undefined)
{
data.switch1=true
}
if (data.switch2===undefined)
{
data.switch2=true
}
if (data.switch3===undefined)
{
data.switch3=true
}
if (data.switch4===undefined)
{
data.switch4=true
}
if (data.id.split("_")[1]==="4G")
{
data.is4G=true
}else
{
data.is4G=false
}
data.device="nothing"
delete data.st;
let sql="SELECT * FROM `remoteswitch` WHERE `id`=?"
db.query(sql,data.id,function(err, rows){
if (1)
{
}
var result=rows
if (result.length===0)
{
console.log(data)
sql="insert into `remoteswitch` ( "+converjsontokeyvalue(data)[0]+" ) values ("+converjsontokeyvalue(data)[1]+")"
console.log(sql)
db.query(sql,(err,result)=>{
console.log(err)
console.log("insert ok")
})
}else
{
sql='update `remoteswitch` set '+converjsontokeyequalvalue(data)+' where id=?'
console.log(sql)
db.query(sql,[data.id],(err,result)=>{
console.log(err)
console.log("update ok")
})
}
})
//console.log(aaa)
}
// console.log('Received message:', topic, message.toString());
});
client.on('reconnect', () => {
console.log('MQTT client reconnected');
});
client.on('offline', () => {
console.log('MQTT client offline');
});
client.on('error', (err) => {
console.error('MQTT client error:', err);
});
// 在退出时关闭客户端连接
process.on('SIGINT', () => {
console.log('Exiting...');
client.end(() => {
console.log('MQTT client disconnected');
process.exit();
});
});
function getdevicemqtt() {
client.publish('topic_who_is_here', 'who is here');
}
exports.getdevicemqtt=getdevicemqtt