当前位置:网站首页>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 {
}
}
}
边栏推荐
- 数商云:从规划到落地,五矿集团如何快速构建数字化发展新格局?
- 见证时代!“人玑协同 未来已来”2022弘玑生态伙伴大会开启直播预约
- 机械设备行业数字化供应链集采平台解决方案:优化资源配置,实现降本增效
- Shell array
- PostgreSQL varchar[] array type operation
- Lean thinking: source, pillar, landing. I understand it after reading this article
- 一次SQL优化,数据库查询速度提升 60 倍
- 生鲜行业B2B电商平台解决方案,提高企业交易流程标准化和透明度
- Intensive cultivation of channels for joint development Fuxin and Weishi Jiajie held a new product training conference
- [pytorch record] automatic hybrid accuracy training torch cuda. amp
猜你喜欢
Solution and summary of Nacos startup failure
Summary of SQL query de duplication statistics methods
kubernetes命令入门(namespaces,pods)
Lake Shore—OptiMag 超导磁体系统 — OM 系列
What must be done in graduation season before going to Shanhai
Parallelism, concurrency and life cycle of threads
Task: denial of service DOS
[go ~ 0 to 1] day 5 July 1 type alias, custom type, interface, package and initialization function
Is PMP cancelled??
MySQL common graphics management tools | dark horse programmers
随机推荐
Facebook聊单,SaleSmartly有妙招!
How to solve the problem of splash screen when the main and sub code streams of easygbs are h.265?
宝,运维100+服务器很头疼怎么办?用行云管家!
M91快速霍尔测量仪—在更短的时间内进行更好的测量
Intensive cultivation of channels for joint development Fuxin and Weishi Jiajie held a new product training conference
微信公众号开发相关流程及功能介绍
Detailed explanation of JUnit unit test framework
物联网平台thingsboard搭建学习记录
MySQL常用图形管理工具 | 黑马程序员
ddr4测试-2
见证时代!“人玑协同 未来已来”2022弘玑生态伙伴大会开启直播预约
Transform + ASM data
下载(导出)pdf模板文件(比如:审批单),报错:Invalid nested tag *** found, expected closing tag ***
精耕渠道共谋发展 福昕携手伟仕佳杰开展新产品培训大会
MySQL common graphics management tools | dark horse programmers
sql查询去重统计的方法总结
【To .NET】C#集合类源码解析
Summary of SQL query de duplication statistics methods
241. Different Ways to Add Parentheses
寶,運維100+服務器很頭疼怎麼辦?用行雲管家!