当前位置:网站首页>物联网平台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 {
}
}
}
边栏推荐
- Yyds dry inventory ravendb start client API (III)
- 【Go ~ 0到1 】 第四天 6月30 defer,结构体,方法
- 论文阅读【Learning to Discretely Compose Reasoning Module Networks for Video Captioning】
- B2B e-commerce platform solution for fresh food industry to improve the standardization and transparency of enterprise transaction process
- linux下清理系统缓存并释放内存
- Lake Shore M91快速霍尔测量仪
- 数商云:从规划到落地,五矿集团如何快速构建数字化发展新格局?
- 一次SQL优化,数据库查询速度提升 60 倍
- ACM mm 2022 video understanding challenge video classification track champion autox team technology sharing
- [pytorch record] distributed training dataparallel and distributeddataparallel of the model
猜你喜欢
【直播预约】数据库OBCP认证全面升级公开课
B2B e-commerce platform solution for fresh food industry to improve the standardization and transparency of enterprise transaction process
数商云:从规划到落地,五矿集团如何快速构建数字化发展新格局?
ACM mm 2022 video understanding challenge video classification track champion autox team technology sharing
Clean up system cache and free memory under Linux
有关 M91 快速霍尔测量仪的更多信息
Lumiprobe 细胞成像研究丨PKH26细胞膜标记试剂盒
Solidity - 算术运算的截断模式(unchecked)与检查模式(checked)- 0.8.0新特性
小红书上的爱情买卖
Games202 operation 0 - environment building process & solving problems encountered
随机推荐
太爱速M源码搭建,巅峰小店APP溢价寄卖源码分享
[6.24-7.1] review of wonderful technical blog posts in the writing community
Solution: you can ping others, but others can't ping me
ES6数组去重的三个简单办法
DTD建模
Love business in Little Red Book
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
数商云:从规划到落地,五矿集团如何快速构建数字化发展新格局?
Shell array
Go language self-study series | go language data type
Bao, what if the O & M 100+ server is a headache? Use Xingyun housekeeper!
Lean thinking: source, pillar, landing. I understand it after reading this article
nacos配置文件发布失败,请检查参数是否正确的解决方案
B2B e-commerce platform solution for fresh food industry to improve the standardization and transparency of enterprise transaction process
MySQL common graphics management tools | dark horse programmers
Bao, que se passe - t - il si le serveur 100 + O & M a mal à la tête? Utilisez le majordome xingyun!
生鲜行业B2B电商平台解决方案,提高企业交易流程标准化和透明度
How to use the low code platform of the Internet of things for personal settings?
Chaos engineering platform chaosblade box new heavy release
Getting started with kubernetes command (namespaces, pods)