wangrong
2025-09-23 f19a0e925da02a08b88784a534b16ec6d833df4c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# -*- coding: utf-8 -*-
 
#!/usr/bin/python
# -*- coding: utf-8 -*
 
import paho.mqtt.client as mqtt
import json
import pymysql
import time
from queue import LifoQueue
from mysqlhelper import MySqLHelper
 
 
def gettime():
    time1=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
    return time1
 
# 服务器地址
host = '7.65.0.207'
# 通信端口 默认端口1883
port = 1883
 
 
username = 'eadpoint'
password = '321123'
 
jsonLte,jsonDevice,jsonGnss,jsonBluetooth,jsonPhone,jsonNr = {}, {}, {}, {}, {}, {}
dictLte, dictDevice, dictGnss, dictPhone, dictNr = {}, {}, {}, {}, {}
merged_list = {}
#LIFO即Last in First Out,后进先出。与栈的类似,使用也很简单,maxsize用法同上
lqLte = LifoQueue(maxsize=0)
lqDevice = LifoQueue(maxsize=0)
lqGnss = LifoQueue(maxsize=0)
lqBluetooth = LifoQueue(maxsize=0)
lqPhone = LifoQueue(maxsize=0)
lqNr = LifoQueue(maxsize=0)
lqWifi = LifoQueue(maxsize=0)
 
# 订阅主题名
arr_topic = ['RadarRecord']
 
db = MySqLHelper()
 
# 连接后事件
def on_connect(client, userdata, flags, respons_code):
    if respons_code == 0:
        # 连接成功
        print('Connection Succeed!')
    else:
        # 连接失败并显示错误代码
        print('Connect Error status {0}'.format(respons_code))
    # 订阅信息
    #client.subscribe(topic)
    for x in arr_topic:
        client.subscribe(x)
 
# 接收到数据后事件
def on_message(client, userdata, msg):
    global dddd
    # 打印订阅消息主题
    print(msg.payload)
    try:
        jsondata=json.loads(msg.payload)
        savejsondata(jsondata)
    except Exception as e:
        print(f"发生了异常: {e}")
 
 
def main():
    client = mqtt.Client()
    # 注册事件
    client.on_connect = on_connect
    client.on_message = on_message
    # 设置账号密码(如果需要的话)
    client.username_pw_set(username, password=password)
    # 连接到服务器
    client.connect(host, port=port, keepalive=60)
    # 守护连接状态
    client.loop_forever()
 
#MySQL保存
def savejsondata(msgdata):
    # SQL 插入语句
    try:
        sql2 = 'insert into dt_radar_message (msgCnt,minOfYear,second,deviceTime,fusDevID,cellid,nofobjects,fps,dataSource,msgdata) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'
        ret = db.insertone(sql2, (msgdata['msgCnt'],msgdata['minOfYear'],msgdata['second'],msgdata['time'],msgdata['fusDevID'],msgdata['cellid'],msgdata['nofobjects'],msgdata['fps'],msgdata['dataSource'],json.dumps(msgdata)))
        print(f"数据库保存成功 {ret}:!")
    except :
        pass
 
if __name__ == '__main__':
    main()