当前位置:网站首页>Learning records of building thingsboard, an Internet of things platform
Learning records of building thingsboard, an Internet of things platform
2022-07-01 19:31:00 【Infinitesimal pawn】
summary : stay thingsboard Download the installation package on the official website , Install and configure according to the documents provided on the official website thingsboard service . adopt esp32 Analog intelligent node , Use mqtt The protocol reports the data to the platform , Conduct dynamic visual display . And pass wereshark Capture the... In the reporting process mqtt message , Conduct safety analysis . The content of the task is to do a safety analysis demo.
Build the technology stack involved :
PostgreSQL+Rabbitmq+MQTTBox-win
Relevant codes generated :
esp32 function microPy Code analog terminal generates temperature data :
import network
import time
import random
import machine
import json
import ubinascii
from simple import MQTTClient
SSID="WiFi name "
PASSWORD=" Yours wifi password "
CLIENT_ID = ubinascii.hexlify(machine.unique_id())
CONFIG = {
"server": "192.168.31.11", # ThingsBoard Address
"port":1883, # MQTT port ( Default 1883)
"mqtt_user": "TCCWopryNcNCSl8iSo3Q", # Access token of the device
"mqtt_password": "TCCWopryNcNCSl8iSo3Q", # Access token of the device
"mqtt_topic": "v1/devices/me/telemetry", # MQTT The theme
}
# Connect WiFi function
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)
# Get the temperature and humidity function
def get_humiture():
d = random.randint(0,100)
return d
# Upload temperature and humidity to ThingsBoard function
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(" About to enter the cycle !")
while True:
tem=get_humiture()
pub_humiture(tem)
time.sleep(5)
if __name__ == "__main__":
main()
Java Intermediate version :
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(" Start execution DHT Method *************************");
String HOST = "tcp://127.0.0.1:1883"; //TBip Address and mqtt port
String TOPIC = "v1/devices/me/telemetry";//TB Telemetry data API Interface
String clientid = "jmqttThingsBoardClient";
MqttClient client=null;
MqttConnectOptions options;
MqttTopic topic;
String username="TCCWopryNcNCSl8iSo3Q";// Device key
try {
// host For host name ,clientid I.e. connection MQTT The client of ID, It is usually represented by a unique identifier ,MemoryPersistence Set up clientid The form of preservation , The default is to save in memory
client = new MqttClient(HOST, clientid, new MemoryPersistence());
// MQTT Connection settings for
options = new MqttConnectOptions();
// Set whether to clear session, Here, if it is set to false Indicates that the server will keep the connection record of the client , I'm going to set it to true Indicates that every time you connect to the server, you connect as a new identity
options.setCleanSession(true);
// Set the user name of the connection
options.setUserName(username);// Device key
// Set the password for the connection
//options.setPassword(passWord.toCharArray());
// Set timeout The unit is in seconds
options.setConnectionTimeout(10);
// Set session heartbeat time The unit is in seconds The server will every 1.5*20 Seconds to send a message to the client to determine whether the client is online , But this method has no mechanism of reconnection
options.setKeepAliveInterval(20);
// Set back
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 Method , If you need to know whether the client is offline in the project, you can call this method . Set notification messages for the final port
options.setWill(topic, "close".getBytes(), 2, true);
client.connect(options);
// sendCon = "{\"temperature\":\"25\",\"humidity\":\"12\",\"light\":\"255\"}";//json Format
client.publish(TOPIC, content.getBytes(), 0, false);// Push data to tb On
} catch (MqttException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} finally {
}
}
}
边栏推荐
- MATLAB中subplot函数的使用
- English语法_形容词/副词3级 -注意事项
- Love business in Little Red Book
- Case sharing: basic networking configuration of QinQ
- The intelligent epidemic prevention system provides safety guarantee for the resumption of work and production at the construction site
- kubernetes命令入门(namespaces,pods)
- Solidity - 合约结构 - 错误(error)- ^0.8.4版本新增
- ddr4测试-2
- C-end dream is difficult to achieve. What does iFLYTEK rely on to support the goal of 1billion users?
- Specification of lumiprobe reactive dye indocyanine green
猜你喜欢

Nacos configuration file publishing failed, please check whether the parameters are correct solution

数商云:从规划到落地,五矿集团如何快速构建数字化发展新格局?

制造业SRM管理系统供应商全方位闭环管理,实现采购寻源与流程高效协同

Lumiprobe 细胞成像研究丨PKH26细胞膜标记试剂盒

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

机械设备行业数字化供应链集采平台解决方案:优化资源配置,实现降本增效

nacos配置文件发布失败,请检查参数是否正确的解决方案

Introduction to relevant processes and functions of wechat official account development

The use of subplot function in MATLAB

论文泛读【FiLM: Visual Reasoning with a General Conditioning Layer】
随机推荐
Solidity - contract structure - error - ^0.8.4 NEW
Write it down once Net travel management background CPU Explosion Analysis
Les canaux de culture intensive s'efforcent de développer Fu Xin et Wei Shi jiajie pour organiser une conférence de formation sur les nouveaux produits
Lake Shore—OptiMag 超导磁体系统 — OM 系列
[info() method in org.slf4j.logger]
EasyGBS网络不稳定情况下重复请求视频拉流问题的优化
Case sharing: basic networking configuration of QinQ
Supervarimag superconducting magnet system SVM series
Nacos configuration file publishing failed, please check whether the parameters are correct solution
【To .NET】C#集合类源码解析
XML syntax, constraints
论文阅读【Discriminative Latent Semantic Graph for Video Captioning】
测试自学人必看:软件测试如何找测试项目?
MySQL常用图形管理工具 | 黑马程序员
Lake Shore - crx-em-hf low temperature probe station
【pytorch记录】自动混合精度训练 torch.cuda.amp
kubernetes命令入门(namespaces,pods)
智慧防疫系统为建筑工地复工复产提供安全保障
Extensive reading of the paper [film: visual reasoning with a general condition layer]
Bao, what if the O & M 100+ server is a headache? Use Xingyun housekeeper!