createLocus.py
9.72 KB
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
#!/usr/bin/python
# -*- coding:utf-8 -*-
import re
import random
import datetime
import pandas as pd
from pandas import DataFrame
from kafka import KafkaConsumer, TopicPartition
from kafka import KafkaProducer
from kafka.errors import KafkaError
import traceback,happybase
from thrift.protocol import TBinaryProtocol
from thrift.transport import THttpClient
# 下面的模块通过 thrift --gen py hbase.thrift 来生成
import sys
sys.path.append("../")
from kafka_protobuffer.kafka_gps_pb2 import TrackDataReq,BaseStReq,WifiInfoReq,GPSAndBSReq
from myhbase import THBaseService
from myhbase.ttypes import TColumnValue, TColumn, TTableName, TTableDescriptor, TColumnFamilyDescriptor, TNamespaceDescriptor, TGet, TPut, TScan
import logging
LOG_FORMAT = "%(asctime)s.%(msecs)03d[%(levelname)s][%(filename)s:%(lineno)d] > %(message)s" # 日志格式化输出
DATE_FORMAT = "%m-%d-%Y %H:%M:%S" # 日期格式
fp = logging.FileHandler(f"createLocus_{datetime.datetime.now().strftime('%Y-%m-%d')}.log", encoding='utf-8')
fs = logging.StreamHandler()
logging.basicConfig(level=logging.CRITICAL, format=LOG_FORMAT, datefmt=DATE_FORMAT, handlers=[fp, fs]) # 调用
#高效率的生产者模块
# from confluent_kafka import Producer,Consumer
# p = Producer(
# {
# 'bootstrap.servers': 'qc131:9092',
# 'session.timeout.ms': 30000,
# 'auto.offset.reset': 'earliest',
# 'api.version.request': False,
# 'broker.version.fallback': '0.8.1.1',
# 'group.id': 'python-producer'
# }
# )
class gpsInfo:
def __init__(self,sn='',lng=0,lat=0,gpsTime='',speed=0,accessTime=''):
self.sn = sn
self.lng = lng
self.lat = lat
self.gpsTime=gpsTime
self.speed = speed
self.accessTime = accessTime
def connect_hbase_test():
#记得启动thrift
#/usr/local/hadoopcluster/hbase/bin/hbase-daemon.sh start thrift
#/opt/glsx-projects/java-projects/zlq/hbase-client/alihbase-2.0.14/bin/hbase-daemon.sh start thrift
connection = happybase.Connection(host='192.168.3.246', port=9090, timeout=None,
autoconnect=True, table_prefix=None, table_prefix_separator=b'_',
compat='0.94', transport='buffered'
)
connection.open()
# l_tables = connection.tables() #获取所有表
# 对应需要关系
# connection.close()
return connection
#gps_gpsdata_change,device_state_change,gps_basestation_change,gps_gpsandbs_change
def connect_hbase():
headers={}
# 线上外网
url = "http://ld-wz9qs00b91uucde9j-proxy-hbaseue-pub.hbaseue.rds.aliyuncs.com:9190"
# 线上内网
# url = "http://ld-wz9qs00b91uucde9j-proxy-hbaseue.hbaseue.rds.aliyuncs.com:9190"
transport = THttpClient.THttpClient(url)
headers["ACCESSKEYID"]="root"
# 密码
headers["ACCESSSIGNATURE"]="root"
transport.setCustomHeaders(headers)
protocol = TBinaryProtocol.TBinaryProtocolAccelerated(transport)
client = THBaseService.Client(protocol)
transport.open()
return client
# GPS、GPRS最新连接时间
def getGPSinfoByHbase(connection, tableName, sn,startTime,endTime):
tableInbytes = "default:"+ tableName # 表,行,dataFrame,转化输出
tableInbytes = tableInbytes.encode("utf8")
#05-00001000000000-20201217101700
row_start ='05-0000' + str(sn)
row_stop ='05-0000' + str(sn)
if len(sn) == 11:
row_start='05-000'+sn
row_stop='05-000'+sn
row_start += f"-{startTime}"
row_stop += f"-{endTime}"
scan = TScan(startRow=row_start.encode("utf8"),stopRow=row_stop.encode("utf8"),limit=1)
currentResults = connection.getScannerResults(tableInbytes, scan, 99999)
gpsInfoList = []
for itemResult in currentResults:
try:
a = itemResult
except:
return 'nan'
b = str(a).split('TColumnValue')
lng = 0
lat=0
speed=0
gpstime=''
accessTime=''
for val in b:
if 'gpsTime' in val:
gpsTime = re.search("value=b'(.*)'",val).group(1)
elif 'longitude' in val:
lng = int(float(re.search("value=b'(.*)'", val).group(1))*1000000)
elif 'latitude' in val:
lat = int(float(re.search("value=b'(.*)'", val).group(1))*1000000)
elif 'speed' in val:
speed = int(re.search("value=b'(.*)'",val).group(1))
elif 'accessTime' in val:
accessTime = re.search("value=b'(.*)'",val).group(1)
gpsInfoList.append(gpsInfo(sn,lng,lat,gpsTime,speed,accessTime))
return gpsInfoList
def producer_demo(SerializeToString,broker,topic,partition):
producer = KafkaProducer(bootstrap_servers=[broker],api_version = (0,8,1,1))
future = producer.send(topic,value=SerializeToString,partition=partition) # 向分区0发送消息
# print(f"send {SerializeToString}")
try:
future.get(timeout=2) # 监控是否发送成功
except KafkaError: # 发送失败抛出kafka_errors
print(traceback.format_exc())
kafka_broker = 'qc131:9092'
# kafka_broker = '192.168.5.17:9093'
def sendBufferToKafka(info):
req = TrackDataReq()
req.devicesn = info.sn
req.facid = 'glsx'
# req.svrtime = int(datetime.datetime.now().timestamp())
req.svrtime = int(datetime.datetime.strptime(info.accessTime,'%Y-%m-%d %H:%M:%S').timestamp())
gpsdata = req.gpsdata.add()
gpsdata.longitude = info.lng
gpsdata.latitude = info.lat
# gpsdata.time = int(datetime.datetime.now().timestamp())
gpsdata.time = int(datetime.datetime.strptime(info.gpsTime, '%Y-%m-%d %H:%M:%S').timestamp())
# gpsdata.time = int(datetime.now().timestamp()-random.randint(0,60*60*24))
gpsdata.speed = int(info.speed)
gpsdata.direction = 0
gpsdata.alt = 0
gpsdata.valid = 'A'
print(f"{req.devicesn},{info.gpsTime},{info.lng},{info.lat},{gpsdata.speed}")
producer_demo(req.SerializeToString(), kafka_broker, 'gps_gpsdata', 0)
def sendGpsAndBsToKafka(info):
req = GPSAndBSReq()
req.devicesn = info.sn
req.svrtime = int(datetime.datetime.strptime(info.accessTime,'%Y-%m-%d %H:%M:%S').timestamp())
req.gpsdata.longitude = info.lng
req.gpsdata.latitude = info.lat
req.gpsdata.time = int(datetime.datetime.strptime(info.gpsTime, '%Y-%m-%d %H:%M:%S').timestamp())
req.gpsdata.speed = int(info.speed)
req.gpsdata.valid = 'A'
req.gpsdata.direction = 0
req.gpsdata.alt = 0
req.mcc = 460
req.mnc = 0
req.bscnt = 1
bstdata = req.bstdata.add()
bstdata.lac = 34067
bstdata.cellid = 142713602
bstdata.signal = 66
req.num = 6
req.voltage = "12V"
print(f"{req.devicesn},{info.gpsTime},{info.lng},{info.lat},{info.speed}")
producer_demo(req.SerializeToString(), kafka_broker, 'gps_gpsandbs', 0)
def getGPSinfoByHbase_test(connection, tableName, sn,startTime,endTime):
tableInbytes = "default:" + tableName # 表,行,dataFrame,转化输出
tableInbytes = tableInbytes.encode("utf8")
# 05-00001000000000-20201217101700
row_start = '05-0000' + str(sn)
row_stop = '05-0000' + str(sn)
if len(sn) == 11:
row_start = '05-000' + sn
row_stop = '05-000' + sn
row_start += f"-{startTime}"
row_stop += f"-{endTime}"
table = happybase.Table(tableInbytes, connection)
# 获取一个扫描器,返回一个generator
scanner = table.scan(row_start=row_start, row_stop=row_stop)
gpsInfoList = []
lng = 0
lat = 0
speed = 0
gpstime = ''
accessTime = ''
for rowkey, v in scanner:
hasValue = True
for index in v.keys():
# print(type(index)) # bytes.decode(index) bytes 类型转 str
if bytes.decode(index) == "info:accessTime":
accessTime = bytes.decode(v[index])
elif bytes.decode(index) == "info:gpsTime":
gpstime = bytes.decode(v[index])
elif bytes.decode(index) == "info:latitude":
lat = float(bytes.decode(v[index]))
elif bytes.decode(index) == "info:longitude":
lng = float(bytes.decode(v[index]))
elif bytes.decode(index) == "info:speed":
speed = int(bytes.decode(v[index]))
gpsInfoList.append(gpsInfo(sn, int(lng*1000000), int(lat*1000000), gpstime, speed, accessTime))
if hasValue is False:
return None
return gpsInfoList
# 1510802141 激活时间:2021-12-07 16:45:43
# 1511213547 激活时间:2022-02-28 20:23:40
# 1511213035 激活时间:2022-01-14 13:21:22
# snList = ['1511213035','1510802141','1511213547']
snList = ['1510118357']
#是否是正式环境
is_upload = False
if __name__ == "__main__":
#从线上同步位置点到测试环境
client = connect_hbase() if is_upload else connect_hbase_test()
for sn in snList:
gpsInfoList = getGPSinfoByHbase(client,'track_gps_2022',sn,'2022112114000','20221121230000') if is_upload else getGPSinfoByHbase_test(client,'track_gps_2022',sn,'2022112114000','20221121230000')
# gpsInfoList = getGPSinfoByHbase(client, 'track_gps', sn, '20220920150000', '20220925000000')
print(len(gpsInfoList))
if len(gpsInfoList) > 0:
for gpsInfo in gpsInfoList:
sendBufferToKafka(gpsInfo)
# sendGpsAndBsToKafka(gpsInfo)
if is_upload is False:
client.close()
#从表格同步位置点到测试环境
# fileData = pd.read_excel("86207100020_行车轨迹.xls")
# print(fileData)
# for i in range(0,len(fileData)):
# gpstime = str(fileData.iloc[i]['时间'])
# timestemp = int(datetime.strptime(gpstime,"%Y-%m-%d %H:%M:%S").timestamp())
# info = gpsInfo(str(fileData.iloc[i]['设备号']),fileData.iloc[i]['经度'],fileData.iloc[i]['纬度'],timestemp,fileData.iloc[i]['速度(km/h)'])
# sendBufferToKafka(info)
print("end")