当前位置:网站首页>物联网平台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 {
}
}
}
边栏推荐
- 如何使用物联网低代码平台进行个人设置?
- B2B e-commerce platform solution for fresh food industry to improve the standardization and transparency of enterprise transaction process
- [6.24-7.1] review of wonderful technical blog posts in the writing community
- Gameframework eating guide
- Lake Shore—OptiMag 超导磁体系统 — OM 系列
- kubernetes命令入门(namespaces,pods)
- AppGallery Connect场景化开发实战—图片存储分享
- ES6数组去重的三个简单办法
- Chinese and English instructions human soluble advanced glycation end products receptor (sRAGE) ELISA Kit
- English语法_形容词/副词3级 -注意事项
猜你喜欢

PMP是被取消了吗??

Example explanation: move graph explorer to jupyterlab

Dom4J解析XML、Xpath检索XML

Viewing the whole ecology of Tiktok from a macro perspective

Solution of intelligent supply chain management platform in aquatic industry: support the digitalization of enterprise supply chain and improve enterprise management efficiency

Chaos engineering platform chaosblade box new heavy release

有关 M91 快速霍尔测量仪的更多信息
![[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?

Graduation season | Huawei experts teach the interview secret: how to get a high paying offer from a large factory?

Huawei game failed to initialize init with error code 907135000
随机推荐
【快应用】text组件里的文字很多,旁边的div样式会被拉伸如何解决
智慧防疫系统为建筑工地复工复产提供安全保障
Clean up system cache and free memory under Linux
Technical secrets of ByteDance data platform: implementation and optimization of complex query based on Clickhouse
[pytorch record] automatic hybrid accuracy training torch cuda. amp
[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
生鲜行业B2B电商平台解决方案,提高企业交易流程标准化和透明度
制造业SRM管理系统供应商全方位闭环管理,实现采购寻源与流程高效协同
Lefse analysis
How to realize the applet in its own app to realize continuous live broadcast
Yyds dry inventory ravendb start client API (III)
Implement a Prometheus exporter
Games202 operation 0 - environment building process & solving problems encountered
Graduation summary
indexof和includes的区别
【Go ~ 0到1 】 第四天 6月30 defer,结构体,方法
M91 fast hall measuring instrument - better measurement in a shorter time
M91快速霍尔测量仪—在更短的时间内进行更好的测量
论文阅读【Learning to Discretely Compose Reasoning Module Networks for Video Captioning】
Chinese and English instructions human soluble advanced glycation end products receptor (sRAGE) ELISA Kit