当前位置:网站首页>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 {
}
}
}
边栏推荐
- 一次SQL优化,数据库查询速度提升 60 倍
- Lake Shore低温恒温器的氦气传输线
- Werewolf killing strategy: do you think I'm easy to cheat? Who do we believe!
- 实现一个Prometheus exporter
- 赋能「新型中国企业」,SAP Process Automation 落地中国
- 数商云:从规划到落地,五矿集团如何快速构建数字化发展新格局?
- Lumiprobe 亚磷酰胺丨六甘醇亚磷酰胺说明书
- 学习笔记-JDBC连接数据库操作的步骤
- Chaos engineering platform chaosblade box new heavy release
- Learning notes - steps of JDBC connection database operation
猜你喜欢

The market value evaporated by 74billion yuan, and the big man turned and entered the prefabricated vegetables

测试自学人必看:软件测试如何找测试项目?
![[live broadcast appointment] database obcp certification comprehensive upgrade open class](/img/38/1ec382d0edda83d4052868255af9ea.jpg)
[live broadcast appointment] database obcp certification comprehensive upgrade open class

有关 M91 快速霍尔测量仪的更多信息

The former 4A executives engaged in agent operation and won an IPO

Task: denial of service DOS

Lumiprobe cell imaging study PKH26 cell membrane labeling kit

kubernetes命令入门(namespaces,pods)

CDGA|从事通信行业,那你应该考个数据管理证书

Intensive cultivation of channels for joint development Fuxin and Weishi Jiajie held a new product training conference
随机推荐
奔赴山海之前,毕业季一定要做的那些事情
transform + asm资料
商业智能BI开发和报表开发有什么本质区别?
Redis 实现限流的三种方式
Solidity - 算术运算的截断模式(unchecked)与检查模式(checked)- 0.8.0新特性
学习笔记【gumbel softmax】
新版国标GB28181视频平台EasyGBS如何配置WebRTC视频流格式播放?
indexof和includes的区别
kubernetes命令入门(namespaces,pods)
ubuntu14安装MySQL并配置root账户本地与远程访问
Netease games, radical going to sea
EasyGBS主子码流都为H.265时,切换出现花屏如何解决?
XML语法、约束
Dom4j parsing XML, XPath retrieving XML
Dlib+Opencv库实现疲劳检测
Instagram 为何从内容共享平台变成营销工具?独立站卖家如何利用该工具?
Lake shore optimag superconducting magnet system om series
Shell array
CDGA|从事通信行业,那你应该考个数据管理证书
ddr4测试-2