first commit
This commit is contained in:
204
server/comman/db.js
Normal file
204
server/comman/db.js
Normal file
@ -0,0 +1,204 @@
|
||||
const mysql = require('mysql')
|
||||
|
||||
const db = mysql.createPool({
|
||||
host: '127.0.0.1',
|
||||
user: 'root',
|
||||
password: '',
|
||||
database: 'remotemqtt',
|
||||
})
|
||||
let queryacy = function( sql, values ) {
|
||||
// 返回一个 Promise
|
||||
return new Promise(( resolve, reject ) => {
|
||||
db.getConnection(function(err, connection) {
|
||||
if (err) {
|
||||
reject( err )
|
||||
} else {
|
||||
connection.query(sql, values, ( err, rows) => {
|
||||
|
||||
if ( err ) {
|
||||
reject( err )
|
||||
} else {
|
||||
resolve( rows )
|
||||
}
|
||||
// 结束会话
|
||||
//console.log(sql);
|
||||
connection.release()
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// const sqlite3 = require('sqlite3').verbose()
|
||||
// //打开或者创建一个数据库
|
||||
|
||||
|
||||
// var db = new sqlite3.Database(
|
||||
// './db.sqlite3',
|
||||
// sqlite3.OPEN_READWRITE,
|
||||
// function (err) {
|
||||
// if (err) {
|
||||
// return console.log(err.message)
|
||||
// }
|
||||
|
||||
// }
|
||||
// )
|
||||
// resetpath=async function(path)
|
||||
// {
|
||||
|
||||
// db = new sqlite3.Database(
|
||||
// path,
|
||||
// sqlite3.OPEN_READWRITE,
|
||||
// function (err) {
|
||||
// if (err) {
|
||||
// return console.log(err.message)
|
||||
// }
|
||||
// console.log('connect database successfully')
|
||||
// }
|
||||
// )
|
||||
// db.run("CREATE TABLE IF NOT EXISTS remoteswitch (\
|
||||
// `AUTOID` INTEGER PRIMARY KEY AUTOINCREMENT,\
|
||||
// `id` tinytext NOT NULL,\
|
||||
// `type` tinytext NOT NULL,\
|
||||
// `tips` text NOT NULL,\
|
||||
// `other` text NOT NULL,\
|
||||
// `switch1` tinyint(1) NOT NULL,\
|
||||
// `switch2` tinyint(1) NOT NULL,\
|
||||
// `switch3` tinyint(1) NOT NULL,\
|
||||
// `switch4` tinyint(1) NOT NULL,\
|
||||
// `is4G` tinyint(1) NOT NULL,\
|
||||
// `device` tinytext DEFAULT NULL)",(err)=>{console.log(err);
|
||||
// })
|
||||
// }
|
||||
|
||||
|
||||
|
||||
// // db.query=db.run
|
||||
// //如果不存在 remoteswitch 表则创建 并打印创建成功 如果错误则打印错误
|
||||
|
||||
// function ConvertoKeyValue(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 ConvertoKeyEQValue(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(",")
|
||||
// }
|
||||
|
||||
db.query("CREATE TABLE IF NOT EXISTS remoteswitch (\
|
||||
AUTOID INT AUTO_INCREMENT PRIMARY KEY,\
|
||||
id TINYTEXT NOT NULL,\
|
||||
type TINYTEXT NOT NULL,\
|
||||
tips TEXT NOT NULL,\
|
||||
other TEXT NOT NULL,\
|
||||
switch1 TINYINT(1) NOT NULL,\
|
||||
switch2 TINYINT(1) NOT NULL,\
|
||||
switch3 TINYINT(1) NOT NULL,\
|
||||
switch4 TINYINT(1) NOT NULL,\
|
||||
is4G TINYINT(1) NOT NULL,\
|
||||
device TINYTEXT DEFAULT NULL\
|
||||
)",(err)=>{;
|
||||
})
|
||||
|
||||
|
||||
|
||||
|
||||
// db.all("CREATE TABLE IF NOT EXISTS remoteswitch1 (\
|
||||
// `AUTOID` INTEGER PRIMARY KEY AUTOINCREMENT,\
|
||||
// `id` tinytext NOT NULL,\
|
||||
// `type` tinytext NOT NULL,\
|
||||
// `tips` text NOT NULL,\
|
||||
// `other` text NOT NULL,\
|
||||
// `switch1` tinyint(1) NOT NULL,\
|
||||
// `switch2` tinyint(1) NOT NULL,\
|
||||
// `switch3` tinyint(1) NOT NULL,\
|
||||
// `switch4` tinyint(1) NOT NULL,\
|
||||
// `is4G` tinyint(1) NOT NULL,\
|
||||
// `device` tinytext DEFAULT NULL)",(err)=>{console.log(err);
|
||||
// })
|
||||
|
||||
|
||||
// let init=async function()
|
||||
// {
|
||||
// db.run("CREATE TABLE IF NOT EXISTS remoteswitch (\
|
||||
// `AUTOID` INTEGER PRIMARY KEY AUTOINCREMENT,\
|
||||
// `id` tinytext NOT NULL,\
|
||||
// `type` tinytext NOT NULL,\
|
||||
// `tips` text NOT NULL,\
|
||||
// `other` text NOT NULL,\
|
||||
// `switch1` tinyint(1) NOT NULL,\
|
||||
// `switch2` tinyint(1) NOT NULL,\
|
||||
// `switch3` tinyint(1) NOT NULL,\
|
||||
// `switch4` tinyint(1) NOT NULL,\
|
||||
// `is4G` tinyint(1) NOT NULL,\
|
||||
// `device` tinytext DEFAULT NULL)",(err)=>{console.log(err);
|
||||
// console.log("remoteswitch table created")})
|
||||
|
||||
// }
|
||||
|
||||
|
||||
// let queryacy = function( sql, values ) {
|
||||
// // 返回一个 Promise
|
||||
// return new Promise(( resolve, reject ) => {
|
||||
// db.getConnection(function(err, connection) {
|
||||
// if (err) {
|
||||
// reject( err )
|
||||
// } else {
|
||||
// connection.query(sql, values, ( err, rows) => {
|
||||
|
||||
// if ( err ) {
|
||||
// reject( err )
|
||||
// } else {
|
||||
// resolve( rows )
|
||||
// }
|
||||
// // 结束会话
|
||||
// //console.log(sql);
|
||||
// connection.release()
|
||||
// })
|
||||
// }
|
||||
// })
|
||||
// })
|
||||
// }
|
||||
|
||||
|
||||
// db.resetpath=resetpath
|
||||
// db.query=db.all
|
||||
db.queryacy= queryacy
|
||||
// db.init=init
|
||||
// db.ConvertoKeyValue=ConvertoKeyValue
|
||||
// db.ConvertoKeyEQValue=ConvertoKeyEQValue
|
||||
module.exports = db
|
458
server/comman/frpclinet.js
Normal file
458
server/comman/frpclinet.js
Normal file
@ -0,0 +1,458 @@
|
||||
const frpserveraxios=require('axios');
|
||||
const herader = {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization':"Basic YWRtaW46bGljYWhr"
|
||||
}
|
||||
const db=require("../comman/db")
|
||||
const mywebsocket=require("./tstws")
|
||||
exports.getfrpserver=getfrpserver
|
||||
|
||||
|
||||
function createdfrpdb( )
|
||||
{
|
||||
const createTableQuery = `
|
||||
CREATE TABLE IF NOT EXISTS frpinfo (
|
||||
autoid BIGINT NOT NULL AUTO_INCREMENT,
|
||||
id VARCHAR(255) NOT NULL,
|
||||
remote_port INT NOT NULL,
|
||||
serial VARCHAR(255) NOT NULL,
|
||||
last_online DATETIME NOT NULL,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
PRIMARY KEY (autoid)
|
||||
) ENGINE = InnoDB;
|
||||
`;
|
||||
|
||||
db.query(createTableQuery, function (error, results, fields) {
|
||||
// if (error) throw error;
|
||||
// console.log('Table created or already exists.');
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
async function insertfrpinfo(data)
|
||||
{
|
||||
|
||||
var insertdata={id:data.nameup,serial:data.serial,name:data.name}
|
||||
|
||||
if(data.status=="online")
|
||||
{
|
||||
insertdata.remote_port=data.conf.remote_port
|
||||
insertdata.last_online=data.nowtime
|
||||
|
||||
}else
|
||||
{
|
||||
insertdata.remote_port=0
|
||||
}
|
||||
//查看看id是否存在
|
||||
let sql="SELECT * FROM `frpinfo` WHERE `id`=?"
|
||||
let result=await db.queryacy(sql,data.nameup)
|
||||
if(result.length==0)
|
||||
{
|
||||
sql="INSERT INTO `frpinfo` SET ?"
|
||||
if(insertdata.remote_port==0)
|
||||
{
|
||||
insertdata.last_online=new Date("2000-01-01").toLocaleString()
|
||||
}
|
||||
|
||||
await db.queryacy(sql,insertdata)
|
||||
//console.log("inserted")
|
||||
}else
|
||||
{
|
||||
//如果remote_port为0 删除emote_port
|
||||
if(insertdata.remote_port==0)
|
||||
{
|
||||
delete insertdata.remote_port
|
||||
}
|
||||
sql="UPDATE `frpinfo` SET ? WHERE `id`='"+data.nameup+"'"
|
||||
await db.queryacy(sql,[insertdata])
|
||||
// console.log("updated")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
async function createdFileInfodb( )
|
||||
{
|
||||
const createTableQuery = 'CREATE TABLE IF NOT EXISTS filebrowerinfo (\
|
||||
`autoid` INT NOT NULL AUTO_INCREMENT,\
|
||||
`name` VARCHAR(255) NOT NULL,\
|
||||
remote_port VARCHAR(255) NOT NULL,\
|
||||
`lasttime` DATETIME NOT NULL,\
|
||||
`sppercent` INT NOT NULL,\
|
||||
`sptotal` FLOAT NOT NULL,\
|
||||
mountedon VARCHAR(255) NOT NULL,\
|
||||
PRIMARY KEY (`autoid`)\
|
||||
) ENGINE = InnoDB;\
|
||||
';
|
||||
|
||||
db.query(createTableQuery, function (error, results, fields) {
|
||||
if (error) throw error;
|
||||
console.log('Table created or already exists.');
|
||||
});
|
||||
}
|
||||
// createdFileInfodb();
|
||||
// createdfrpdb();
|
||||
// getfrpserver();
|
||||
let devlistname=[]
|
||||
async function getfrpserver()
|
||||
{
|
||||
devlistname=[];
|
||||
createdFileInfodb();
|
||||
createdfrpdb();
|
||||
|
||||
sql='SELECT * FROM `filebrowerinfo` WHERE 1'
|
||||
let result=await db.queryacy(sql)
|
||||
// console.log(result)
|
||||
for (var i=0;i<result.length;i++)
|
||||
{
|
||||
devlistname.push(result[i].name)
|
||||
}
|
||||
|
||||
|
||||
var aaa=await frpserveraxios.get('http://106.75.72.40:7500/api/proxy/tcp',{headers:herader})
|
||||
nowtime=new Date()
|
||||
nowtime=nowtime.toLocaleString()
|
||||
aaa=aaa.data.proxies;
|
||||
for (var i=0;i<aaa.length;i++)
|
||||
{
|
||||
|
||||
if(aaa[i].name.endsWith('_data'))
|
||||
{
|
||||
var data=aaa[i]
|
||||
//console.log(aaa[i].name)
|
||||
//去除后缀
|
||||
var name=aaa[i].name.replace('_data','')
|
||||
//console.log(name)
|
||||
name=name.toUpperCase()
|
||||
var list=name.split('_')
|
||||
var serial=list[list.length-1]
|
||||
data.serial=serial
|
||||
data.nowtime=nowtime
|
||||
|
||||
data.nameup=name
|
||||
if (data.name=="TowerIS2_2006_data")
|
||||
{
|
||||
//将data.nameup 从devlistname中删除
|
||||
console.log("delete TowerIS2_2006_data")
|
||||
|
||||
}
|
||||
|
||||
|
||||
if (data.conf!=null && devlistname.includes(data.nameup))
|
||||
{
|
||||
//将data.nameup 从devlistname中删除
|
||||
let index=devlistname.indexOf(data.nameup)
|
||||
devlistname.splice(index,1)
|
||||
console.log("delete "+data.nameup)
|
||||
console.log(devlistname);
|
||||
|
||||
|
||||
}
|
||||
|
||||
if(data.nameup=="NOCONFIG")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// console.log(data.name)
|
||||
//年月日时分秒
|
||||
insertfrpinfo(data);
|
||||
//插入数据库 构建object
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
if(name.startsWith('TowerIS2'.toUpperCase()))
|
||||
{
|
||||
//将name转换为大写
|
||||
|
||||
await dealwithIS2(data)
|
||||
}
|
||||
if(name.startsWith('TOWER_ISIF')||name.startsWith('TOWER_OSIF'))
|
||||
{
|
||||
//将name转换为大写
|
||||
|
||||
await dealwithISIF(data)
|
||||
}
|
||||
if(name.startsWith('ASD_S'))
|
||||
{
|
||||
//将name转换为大写
|
||||
|
||||
await dealwithASD(data)
|
||||
}
|
||||
// // console.log("name:"+name+"\tserial:"+i+" "+name.startsWith('TOWER_OSIF'))
|
||||
|
||||
// if(name.startsWith('TOWER_OSIF'))
|
||||
// {
|
||||
// await dealwithISIF(data)
|
||||
// }
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
console.log(devlistname)
|
||||
console.log("done")
|
||||
}
|
||||
|
||||
async function dealwithIS2(data)
|
||||
{
|
||||
// console.log(data)
|
||||
|
||||
// console.log("im IS2 my serial is:"+data.serial+"\tmy name is:"+data.nameup)
|
||||
await panduanshebei(data)
|
||||
|
||||
}
|
||||
|
||||
async function dealwithISIF(data)
|
||||
{
|
||||
// console.log("im ISIF my serial is:"+data.serial+"\tmy name is:"+data.nameup)
|
||||
|
||||
await panduanshebei(data)
|
||||
|
||||
}
|
||||
async function dealwithASD(data)
|
||||
{
|
||||
// console.log("im OSIF my serial is:"+data.serial+"\tmy name is:"+data.nameup)
|
||||
await panduanshebei(data)
|
||||
}
|
||||
|
||||
async function insettofilebrowerinfo(data)
|
||||
{
|
||||
let sql="SELECT * FROM `filebrowerinfo` WHERE `name`='"+data.name+"'"
|
||||
let result=await db.queryacy(sql)
|
||||
if(result.length==0)
|
||||
{
|
||||
sql="INSERT INTO `filebrowerinfo` SET ?"
|
||||
await db.queryacy(sql,data)
|
||||
}else
|
||||
{
|
||||
sql="UPDATE `filebrowerinfo` SET ? WHERE `name`='"+data.name+"'"
|
||||
await db.queryacy(sql,data)
|
||||
}
|
||||
}
|
||||
async function panduanshebei(data)
|
||||
{
|
||||
if(data.conf!=null)
|
||||
{
|
||||
let frpret=await getdevicelastdatatime(data.conf)
|
||||
let timelast= frpret.timelast
|
||||
|
||||
let dataforinsert=
|
||||
|
||||
{
|
||||
name:data.nameup,
|
||||
lasttime:frpret.lasttimedata,
|
||||
sppercent:frpret.space.percent,
|
||||
sptotal:frpret.space.total/1024/1024+"GB",
|
||||
remote_port:"http://106.75.72.40:"+data.conf.remote_port,
|
||||
mountedon:frpret.space.mountedon
|
||||
|
||||
}
|
||||
|
||||
if (timelast<24.5)
|
||||
{
|
||||
console.log(data.name+"\t数据正常 "+timelast+"小时内新的日期文件创建");
|
||||
await insettofilebrowerinfo(dataforinsert)
|
||||
|
||||
|
||||
|
||||
}else if(timelast==100000)
|
||||
{
|
||||
console.log("\x1b[33m"+data.name+"\t数据管理页面无法打开 请检查设备是否正常连接 \x1b[0m");
|
||||
}
|
||||
else
|
||||
{
|
||||
console.log("\x1b[31m"+data.name+"\t严重错误 数据异常"+timelast+"小时内没有新的日期文件创建 \x1b[0m");
|
||||
await insettofilebrowerinfo(dataforinsert)
|
||||
}
|
||||
|
||||
|
||||
|
||||
}else{
|
||||
|
||||
|
||||
console.log("\x1b[33m"+ data.name+"\t设备未连接 \x1b[0m")
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
async function getdevicelastdatatime(device)
|
||||
{
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
var ret={
|
||||
timelast:100000,
|
||||
space:{
|
||||
percent:0,
|
||||
total:0,
|
||||
mountedon:" "
|
||||
}
|
||||
}
|
||||
|
||||
// console.log(device)
|
||||
let port=device.remote_port;
|
||||
let logaddress="http://106.75.72.40:"+port+"/api/login"
|
||||
let passbody={
|
||||
"username":"admin",
|
||||
"password":"licahk"
|
||||
}
|
||||
|
||||
|
||||
let loginkey="";
|
||||
try {
|
||||
loginkey = await frpserveraxios.post(logaddress, passbody);
|
||||
// 请求成功的处理逻辑
|
||||
} catch (error) {
|
||||
loginkey= 'ECONNRESET';
|
||||
// 请求失败的处理逻辑
|
||||
if (error.code === 'ECONNRESET') {
|
||||
// 处理 socket hang up 错误
|
||||
|
||||
} else {
|
||||
// 其他类型的错误处理
|
||||
|
||||
}
|
||||
}
|
||||
if(loginkey=='ECONNRESET')
|
||||
{
|
||||
ret.timelast=100000
|
||||
return ret
|
||||
}
|
||||
|
||||
//let loginkey=await frpserveraxios.post(logaddress,passbody).catch((err)=>{console.log(err)})
|
||||
loginkey=loginkey.data;
|
||||
let dataaddress="http://106.75.72.40:"+port+"/api/resources";
|
||||
let datainfo=await frpserveraxios.get(dataaddress,{headers:{'X-Auth':loginkey}});
|
||||
datainfo=datainfo.data;
|
||||
//console.log(datainfo);
|
||||
filelist=datainfo.items;
|
||||
let diff=100000;
|
||||
filelist.forEach(file => {
|
||||
|
||||
if(file.path.toUpperCase()=="DATA")
|
||||
{
|
||||
|
||||
let filemodtime=file.modified
|
||||
//计算与当前时间的差值 modified 举例2024-07-12T05:00:40.664988617+08:00
|
||||
let now=new Date()
|
||||
let nowtime=now.getTime()
|
||||
|
||||
let filetime=new Date(filemodtime)
|
||||
ret.lasttimedata=filetime.toLocaleString();
|
||||
let filetime1=filetime.getTime()
|
||||
|
||||
diff=nowtime-filetime1
|
||||
diff=diff/1000/3600
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
ret.timelast=diff
|
||||
|
||||
if(port==13012)
|
||||
{
|
||||
ret.space.percent=0
|
||||
ret.space.total=0
|
||||
}
|
||||
|
||||
|
||||
var wsaddres="ws://106.75.72.40:"+port+"/api/command/?auth="+loginkey;
|
||||
var message="df /dev/mmcblk1p1"
|
||||
var aa=await mywebsocket.runinws(message,wsaddres)
|
||||
let commandret=aa[0].toString()
|
||||
if(commandret=="error")
|
||||
{
|
||||
ret.space.percent=0
|
||||
ret.space.total=0
|
||||
}
|
||||
else if(commandret=="Command not allowed.")
|
||||
{
|
||||
console.log("Command not allowed")
|
||||
console.log("\x1b[31m"+device.proxy_name +" need allow df in filebrowser\x1b[0m")
|
||||
}
|
||||
else
|
||||
{
|
||||
if(aa.length==1)
|
||||
{
|
||||
let cc=aa[0].toString()
|
||||
let bb=cc.split(":")
|
||||
if(bb.length==3)
|
||||
{
|
||||
if (bb[2].trim()==" No such file or directory".trim())
|
||||
{
|
||||
console.log("No such file or directory")
|
||||
ret.space.percent=0
|
||||
ret.space.total=0
|
||||
ret.space.mountedon="No SD card"
|
||||
//return ret
|
||||
}
|
||||
}
|
||||
console.log("error")
|
||||
aa.push(Buffer.from("udev aa bb"))
|
||||
}
|
||||
let data=aa[1].toString()
|
||||
let space=data.split(" ")
|
||||
//移除space中的空格
|
||||
space=space.filter(function(s) {
|
||||
return s && s.trim();
|
||||
});
|
||||
|
||||
|
||||
|
||||
if(space[0]=="udev")
|
||||
{
|
||||
message="df /home"
|
||||
aa=await mywebsocket.runinws(message,wsaddres)
|
||||
data=aa[1].toString()
|
||||
space=data.split(" ")
|
||||
space=space.filter(function(s) {
|
||||
return s && s.trim();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
ret.space.percent=space[4]
|
||||
ret.space.total=space[1]
|
||||
if(ret.space.mountedon!="No SD card")
|
||||
ret.space.mountedon=space[5]
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
return ret;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// runinws("df /dev/mmcblk1p1","ws://106.75.72.40:30012/api/command/?auth=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoxLCJsb2NhbGUiOiJ6aC1jbiIsInZpZXdNb2RlIjoibGlzdCIsInNpbmdsZUNsaWNrIjpmYWxzZSwicGVybSI6eyJhZG1pbiI6dHJ1ZSwiZXhlY3V0ZSI6dHJ1ZSwiY3JlYXRlIjp0cnVlLCJyZW5hbWUiOnRydWUsIm1vZGlmeSI6dHJ1ZSwiZGVsZXRlIjp0cnVlLCJzaGFyZSI6dHJ1ZSwiZG93bmxvYWQiOnRydWV9LCJjb21tYW5kcyI6WyJkZiJdLCJsb2NrUGFzc3dvcmQiOmZhbHNlLCJoaWRlRG90ZmlsZXMiOmZhbHNlfSwiZXhwIjoxNzIxMDM3MjE0LCJpYXQiOjE3MjEwMzAwMTQsImlzcyI6IkZpbGUgQnJvd3NlciJ9.YNDbRregnpkZw6UFS0EJjX0DcCFQQoFmnCCusyFzstQ" )
|
158
server/comman/mqqtclinet.js
Normal file
158
server/comman/mqqtclinet.js
Normal file
@ -0,0 +1,158 @@
|
||||
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
|
59
server/comman/mqqthttp.js
Normal file
59
server/comman/mqqthttp.js
Normal file
@ -0,0 +1,59 @@
|
||||
const axios=require("./mqttaxios");
|
||||
|
||||
async function queryDeviceStatus(deviceId) {
|
||||
try {
|
||||
const response = await axios.get('/api/v4/clients/', {
|
||||
params: {
|
||||
clientid: deviceId
|
||||
}
|
||||
});
|
||||
//cl console.log(response)
|
||||
const clients = response.data.data;
|
||||
if (clients.length > 0) {
|
||||
|
||||
console.log(clients[0].connected);
|
||||
console.log("on working");
|
||||
return clients[0].connected;
|
||||
} else {
|
||||
|
||||
console.log("not on working");
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async function queryalldeviceonline() {
|
||||
const listofcliensidonline=new Array();
|
||||
try {
|
||||
const response = await axios.get('/api/v4/clients/');
|
||||
//cl console.log(response)
|
||||
const clients = response.data.data;
|
||||
|
||||
for (item in clients)
|
||||
{
|
||||
// console.log(clients[item])
|
||||
listofcliensidonline.push(clients[item].clientid);
|
||||
}
|
||||
|
||||
console.log(listofcliensidonline)
|
||||
return listofcliensidonline;
|
||||
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return listofcliensidonline;
|
||||
}
|
||||
}
|
||||
|
||||
function queryDeviceStatus(clientid,list)
|
||||
{
|
||||
return list.includes(clientid);
|
||||
|
||||
|
||||
}
|
||||
|
||||
exports.queryalldeviceonline=queryalldeviceonline;
|
||||
//queryalldeviceonline()
|
10
server/comman/mqttaxios.js
Normal file
10
server/comman/mqttaxios.js
Normal file
@ -0,0 +1,10 @@
|
||||
const myaxios = require('axios');
|
||||
myaxios.defaults.baseURL = 'http://82.156.1.111:18083';
|
||||
const mqtusername = 'admin';
|
||||
const mqtpassword = 'licahk';
|
||||
const input = mqtusername+":"+mqtpassword;
|
||||
const token = Buffer.from(input).toString('base64');
|
||||
//console.log(token);
|
||||
myaxios.defaults.headers.common['Authorization'] = 'Basic ' + token;
|
||||
|
||||
module.exports = myaxios
|
7
server/comman/mqttclinet.js
Normal file
7
server/comman/mqttclinet.js
Normal file
@ -0,0 +1,7 @@
|
||||
const mqtt = require('mqtt');
|
||||
const db=require("../comman/db")
|
||||
const client = mqtt.connect('mqtt://82.156.1.111:40000', {
|
||||
clientId: 'web_collector',
|
||||
username: 'xin',
|
||||
password: 'irishk'
|
||||
});
|
46
server/comman/tstws.js
Normal file
46
server/comman/tstws.js
Normal file
@ -0,0 +1,46 @@
|
||||
|
||||
const WebSocket = require('ws');
|
||||
|
||||
|
||||
|
||||
async function sendMessageAndWaitForResponse(addres, message) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = new WebSocket(addres);
|
||||
buffarr=[];
|
||||
socket.on('open', () => {
|
||||
socket.send(message);
|
||||
});
|
||||
|
||||
// 监听服务器返回的消息
|
||||
function messageHandler(response) {
|
||||
// 在这里处理服务器返回的消息
|
||||
// 可以根据需要解析 JSON 或其他处理
|
||||
buffarr.push(response)
|
||||
socket.off('error',errorHandler)
|
||||
|
||||
}
|
||||
function errorHandler(err)
|
||||
{
|
||||
console.log(err)
|
||||
buffarr.push(Buffer.from("error"))
|
||||
resolve(buffarr);
|
||||
}
|
||||
|
||||
socket.on('error',errorHandler);
|
||||
// 监听服务器返回的消息
|
||||
socket.on('message', messageHandler);
|
||||
|
||||
// 处理连接关闭情况
|
||||
socket.on('close', () => {
|
||||
resolve(buffarr);
|
||||
});
|
||||
});
|
||||
}
|
||||
async function runinws( message,addres){
|
||||
let aa=await sendMessageAndWaitForResponse(addres,message)
|
||||
|
||||
return aa
|
||||
|
||||
// console.log(aa[1].toString())
|
||||
}
|
||||
exports.runinws=runinws
|
Reference in New Issue
Block a user