如何用Nodejs快速搭建一个调试工具

一、前言

很多时候,我们需要进行一些功能的调试,比如MQTT,比如某个功能脚本,或者是物联网场景下联调测试。这个时候苦于没有趁手的工具,花时间写个测试程序又觉得不值当(对于一个Java项目来说),所以本篇博客教大家用nodejs进行快速调试。

既然选择nodejs,js脚本不是更简单吗?no、no、no,我们主要是想借用npm丰富的生态。

二、案例演示

  1. 首先我们通过express脚手架快速搭建一个项目,或者init一个空项目;
  2. 创建一个文件夹,里边就是我们的脚本文件;
  3. 这里假设我们的场景是MQTT接收消息并存入数据库(6字段字节数分别为212212);
  4. 执行 node mqtt.js 即可进行测试。

测试代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
var mqtt = require('mqtt');
var Sequelize = require('sequelize');

var sequelize = new Sequelize('iot', 'root', 'root',
{
host: '127.0.0.1',
dialect: 'mysql',
timezone:'+08:00',
pool: {
max: 5,
min: 0,
idle: 10000
}
})

var SmallU = sequelize.define('table1', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
},
deviceName:{
type: Sequelize.STRING,
field:'device_name',
comment:"设备id"
},
temperature: {
type: Sequelize.DOUBLE,
comment:"温度"
},
humidity: {
type: Sequelize.DOUBLE,
allowNull: false,
comment: "湿度"
},
pm25: {
type: Sequelize.DOUBLE,
allowNull: false,
comment: "PM2.5"
},
formaldehyde: {
type: Sequelize.DOUBLE,
allowNull: false,
comment: "甲醛"
},
batteryLevel: {
type: Sequelize.STRING,
field:"battery_level",
comment:"电池电量"
},
counter: {
type: Sequelize.INTEGER,
comment:"计数"
}

}, {
underscored: true,//驼峰式
freezeTableName: true,
// paranoid: true
// tableName: 'user_less_add'
});

sequelize.sync({force: false})


//MQTT
var client = mqtt.connect({port: 8883, host: '127.0.0.1', keepalive: 60});
let topic = 'application/7/node/+/rx';
client.subscribe(topic);

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

var data = JSON.parse(message.toString());
console.log("========开始=====");
console.log(data);
console.log("========结束====");
const deviceName = data.deviceName;
var rowData = Buffer(data.data, 'base64')
var temperature = parseInt(rowData.subarray(0,2).toString('hex'),16)/10; //温度
var humidity = parseInt(rowData.subarray(2,3).toString('hex'),16); //湿度
var pm25 = parseInt(rowData.subarray(3,5).toString('hex'),16); //PM2.5
var formaldehyde = parseInt(rowData.subarray(5,7).toString('hex'),16)/1000; //甲醛
var batteryLevel = parseInt(rowData.subarray(7,8).toString('hex'),16); //电池电量
var counter = parseInt(rowData.subarray(8,10).toString('hex'),16); //计数

SmallU.create({
deviceName:deviceName,
temperature:temperature,
humidity:humidity,
pm25:pm25,
formaldehyde:formaldehyde,
batteryLevel:batteryLevel,
counter:counter
})
});

三、最后

本篇博客仅作为工具类进行记录。