当前位置:网站首页>物联网平台thingsboard搭建学习记录
物联网平台thingsboard搭建学习记录
2022-07-01 18:44:00 【无极小卒】
概述:在thingsboard官网下载安装包,根据官网提供的文档进行安装配置thingsboard服务。通过esp32模拟智能节点,使用mqtt协议将数据上报至平台,进行动态的可视化展示。并通过wereshark抓取上报过程中的mqtt报文,进行安全性分析。任务内容做要是做一个安全分析的demo。
搭建所涉及的技术栈:
PostgreSQL+Rabbitmq+MQTTBox-win
产生的相关代码:
esp32运行microPy代码模拟终端产生温度数据:
import network
import time
import random
import machine
import json
import ubinascii
from simple import MQTTClient
SSID="WiFi名称"
PASSWORD="你的wifi密码"
CLIENT_ID = ubinascii.hexlify(machine.unique_id())
CONFIG = {
"server": "192.168.31.11", # ThingsBoard地址
"port":1883, # MQTT端口(默认1883)
"mqtt_user": "TCCWopryNcNCSl8iSo3Q", # 设备的访问令牌
"mqtt_password": "TCCWopryNcNCSl8iSo3Q", # 设备的访问令牌
"mqtt_topic": "v1/devices/me/telemetry", # MQTT主题
}
#连接WiFi函数
def connectWifi(ssid,passwd):
global wlan
wlan=network.WLAN(network.STA_IF)
wlan.active(True)
wlan.disconnect()
wlan.connect(ssid,passwd)
while(wlan.ifconfig()[0]=='0.0.0.0'):
time.sleep(1)
#获取温湿度函数
def get_humiture():
d = random.randint(0,100)
return d
#上传温湿度到ThingsBoard函数
def pub_humiture(temperature):
global c
data={'hello':temperature}
c.publish(CONFIG["mqtt_topic"], json.dumps(data))
print(json.dumps(data))
def main():
connectWifi(SSID,PASSWORD)
global c
c = MQTTClient(CLIENT_ID, CONFIG["server"],CONFIG["port"], CONFIG["mqtt_user"], CONFIG["mqtt_password"])
c.connect()
print("Connected to %s, publish to %s topic" % (CONFIG["server"], CONFIG["mqtt_topic"]))
print("即将进入循环!")
while True:
tem=get_humiture()
pub_humiture(tem)
time.sleep(5)
if __name__ == "__main__":
main()
Java 中间版本:
package org.jmqtt.java;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class ThingsboardClient {
public void toTB(String content){
System.out.println("开始执行DHT方法*************************");
String HOST = "tcp://127.0.0.1:1883"; //TBip地址和mqtt端口
String TOPIC = "v1/devices/me/telemetry";//TB遥测数据API接口
String clientid = "jmqttThingsBoardClient";
MqttClient client=null;
MqttConnectOptions options;
MqttTopic topic;
String username="TCCWopryNcNCSl8iSo3Q";//设备秘钥
try {
// host为主机名,clientid即连接MQTT的客户端ID,一般以唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以内存保存
client = new MqttClient(HOST, clientid, new MemoryPersistence());
// MQTT的连接设置
options = new MqttConnectOptions();
// 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
options.setCleanSession(true);
// 设置连接的用户名
options.setUserName(username);//设备秘钥
// 设置连接的密码
//options.setPassword(passWord.toCharArray());
// 设置超时时间 单位为秒
options.setConnectionTimeout(10);
// 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
options.setKeepAliveInterval(20);
// 设置回
client.setCallback(new MqttCallbackExtended() {
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
String context = new String(message.getPayload());
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
// TODO Auto-generated method stub
}
@Override
public void connectionLost(Throwable cause) {
// TODO Auto-generated method stub
}
@Override
public void connectComplete(boolean reconnect, String serverURI) {
// TODO Auto-generated method stub
}
});
topic = client.getTopic(TOPIC);
//setWill方法,如果项目中需要知道客户端是否掉线可以调用该方法。设置最终端口的通知消息
options.setWill(topic, "close".getBytes(), 2, true);
client.connect(options);
// sendCon = "{\"temperature\":\"25\",\"humidity\":\"12\",\"light\":\"255\"}";//json格式
client.publish(TOPIC, content.getBytes(), 0, false);//推送数据到tb上
} catch (MqttException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} finally {
}
}
}
边栏推荐
- 市值蒸发740亿,这位大佬转身杀入预制菜
- 有关 M91 快速霍尔测量仪的更多信息
- Nacos configuration file publishing failed, please check whether the parameters are correct solution
- Today, with the popularity of micro services, how does service mesh exist?
- MySQL常用图形管理工具 | 黑马程序员
- June issue | antdb database participated in the preparation of the "Database Development Research Report" and appeared on the list of information technology and entrepreneurship industries
- Technical secrets of ByteDance data platform: implementation and optimization of complex query based on Clickhouse
- PostgreSQL varchar[] 数组类型操作
- 苹果产品在日本全面涨价,iPhone13涨19%
- Shell array
猜你喜欢

宝,运维100+服务器很头疼怎么办?用行云管家!

Huawei cloud experts explain the new features of gaussdb (for MySQL)

Learn MySQL from scratch - database and data table operations

【直播预约】数据库OBCP认证全面升级公开课

C-end dream is difficult to achieve. What does iFLYTEK rely on to support the goal of 1billion users?
![[AGC] how to solve the problem that the local display of event analysis data is inconsistent with that in AGC panel?](/img/66/674a06d8e45a31ae879b81554ef373.png)
[AGC] how to solve the problem that the local display of event analysis data is inconsistent with that in AGC panel?

Digital business cloud: from planning to implementation, how does Minmetals Group quickly build a new pattern of digital development?

ACM mm 2022 video understanding challenge video classification track champion autox team technology sharing

Netease games, radical going to sea

有关 M91 快速霍尔测量仪的更多信息
随机推荐
The market value evaporated by 74billion yuan, and the big man turned and entered the prefabricated vegetables
Three ways for redis to realize current limiting
水产行业智能供应链管理平台解决方案:支撑企业供应链数字化,提升企业管理效益
Appgallery connect scenario development practice - image storage and sharing
AppGallery Connect场景化开发实战—图片存储分享
11. Users, groups, and permissions (1)
Viewing the whole ecology of Tiktok from a macro perspective
XML语法、约束
Viewing technological changes through Huawei Corps (VI): smart highway
Go语言高级
[live broadcast appointment] database obcp certification comprehensive upgrade open class
Dom4J解析XML、Xpath检索XML
Summary of the core steps in the life cycle of beans
ES6 summary "suggestions collection" of array methods find(), findindex()
【快应用】Win7系统使用华为IDE无法运行和调试项目
[pytorch record] automatic hybrid accuracy training torch cuda. amp
制造业SRM管理系统供应商全方位闭环管理,实现采购寻源与流程高效协同
[quick application] there are many words in the text component. How to solve the problem that the div style next to it will be stretched
Improve yolov5 with gsconv+slim neck to maximize performance!
宝,运维100+服务器很头疼怎么办?用行云管家!