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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# -*- coding: utf-8 -*-
 
#!/usr/bin/python
# -*- coding: utf-8 -*
 
import paho.mqtt.client as mqtt
import json
import time
from mysqlhelper import MySqLHelper
from linkListUtil import Node, LinkedList
from shapelyUtil import ShapelyUtil
import threading
 
 
def gettime():
    time1=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
    return time1
 
# 服务器地址
host = '7.65.0.207' #'7.65.0.207'
# 通信端口 默认端口1883
port = 1883
 
 
username = 'eadpoint'
password = '321123'
 
merged_list = {}
objs = LinkedList()
currentObjs = []
removeObjIds = []
removeObjs = []
shapeUtil = ShapelyUtil([[12146938.804545141,3106558.9023983314],[12147505.698887747,3106620.0104321464],[12147188.527927307,3108004.3420571982],[12146593.188072586,3107932.8914925163]])
 
arr_topic = ['RadarRecord']
send_topic = ['dfAddObj','dfAddTrack','dfRemoveObj']
 
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 send_file(client, topic, filename):
    try:
        with open(filename, 'r') as file:
            for line in file:
                radarData = json.loads(line)
                #client.publish(topic, payload=json.dumps(radarData), qos=2, retain=False)
                client.publish(topic, line)
                print(f"Sent: {radarData}")
    except Exception as e:
        print(f"发生了异常: {e}")
 
# 接收到数据后事件
def on_message(client, userdata, msg):
    global dddd
    # 打印订阅消息主题
    #print(msg.payload)
    try:
        jsondata=json.loads(msg.payload)
        currentObjs.clear()
        removeObjIds.clear()
        #print(jsondata)
        if jsondata['object'] is None:
            print('has no object data')
        else :
            if jsondata['cellid'] == "11" :
                for x in jsondata['object']:
                    x['time'] = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(x['ts']))
                    x['recvtime'] = int(time.time())
                    x['minOfYear'] = jsondata['minOfYear']
                    x['second'] = jsondata['second']
                    x['direction'] = 0
                    x['fusDevID'] = jsondata['fusDevID']
                    x['fps'] = jsondata['fps']
                    x['cellid'] = jsondata['cellid']
                    x['msgCnt'] = jsondata['msgCnt']
                    x['nofobjects'] = jsondata['nofobjects']
                    x['dataSource'] = jsondata['dataSource']
                    x['refPos'] = jsondata['refPosList'][0]
                    x['isInside'] = 1 if shapeUtil.isInPolygon_(x['lng'],x['lat']) else 0
                    node = objs.find_by_value(x['object_id'])
                    currentObjs.append(x['object_id'])
                    if node is None:
                        objs.insert_value_to_head(x['object_id'], [x])
                        if x['isInside'] == 1:
                            client.publish(send_topic[0], json.dumps(x))
                    else :
                        obj0 = node.track[0]
                        x['direction'] = shapeUtil.angle(obj0['lat'], obj0['lng'], x['lat'], x['lng'])
                        if x['isInside'] == 1:
                            client.publish(send_topic[1], json.dumps(x))
                        node.track.append(x)
    except Exception as e:
        print(f"发生了异常: {e}")
 
def monitor_list(linked_list, client):
    p = linked_list.head
    while True:
        if p is None:
            p = linked_list.head
            continue
        item = p.item
        track = p.track
        if abs(track[-1]['recvtime'] - int(time.time())) > 5 :
            print(f"     {track[-1]['recvtime']}    {int(time.time())}  ")
            client.publish(send_topic[2],item)
            track[-1]['isInside'] = -1
            q = p.next
            linked_list.delete_by_value(p.item, p.track)
            p = q
        else :
            p = p.next
        savejsondata(item, track)
            
 
def main():
    cleanHistorydata()
    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)
    list_thread = threading.Thread(target=monitor_list, args=(objs, client))
    print('------------------------')
    list_thread.start()
    # 守护连接状态
    client.loop_forever()
 
 
#MySQL保存
def savejsondata(object_id, track):
    # SQL 插入语句
    try:
        obj = track[-1]
        sql2 = 'insert into dt_radar_message (object_id,lng,lat,height,minOfYear,second,direction,deviceTime,fusDevID,fps,cellid,msgCnt,nofobjects,dataSource,msgdata,isInside,serverTime,create_time) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now(),now()) on duplicate key update msgdata=values(msgdata), lng=values(lng), lat=values(lat), direction=values(direction), height=values(height), isInside=values(isInside), update_time=now()'
        ret = db.insertone(sql2, (object_id,"{:.8f}".format(obj['lng']),"{:.8f}".format(obj['lat']),"{:.2f}".format(obj['height']),obj['minOfYear'],obj['second'],"{:.2f}".format(obj['direction']),obj['time'],obj['speed'],obj['fps'],obj['cellid'],obj['msgCnt'],obj['nofobjects'],obj['dataSource'],json.dumps(track),obj['isInside']))
        print(f"数据库保存成功 {ret}:!")
    except Exception as e:
        print(e)
        pass
 
#MySQL保存
def cleanHistorydata():
    # SQL 插入语句
    try:
        sql2 = 'update dt_radar_message set isInside = -1 where isInside =1'
        ret = db.update(sql2)
        print(f"数据库保存成功 {ret}:!")
    except Exception as e:
        print(e)
        pass
 
if __name__ == '__main__':
    #print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(1712900732)))
    main()