Commit 37a56c8b by 潘建波

Merge branch 'develop' of http://192.168.9.26/platform/tx1_box_serv into develop

# Conflicts:
#	code/tx1_box_serv/apps/api/http_serv.pyc
#	code/tx1_box_serv/apps/main.py
#	code/tx1_box_serv/apps/special.properties
2 parents 89b4380e 885a8189
......@@ -10,6 +10,7 @@ import apps.gbvar.ws_serv_global as sv_global
import apps.gbvar.database_global as database
import apps.gbvar.dict_properties as dict_p
import apps.commons.editXml as editXml
import apps.commons.event_to_local as etl
tx1_box = Blueprint('tx1_box', __name__)
......@@ -18,13 +19,21 @@ tx1_box = Blueprint('tx1_box', __name__)
def dataRecv():
data = request.get_data()
print data
send_all_data(sv_global.get_value(),data)
dataDic = json.loads(data)
if type(dataDic) is dict:
res = etl.eventToLocal.saveEventToLocal(dataDic)
print(res)
send_all_data(sv_global.get_value(),data)
else:
print('error: data to dict failed, data:{}'.format(data))
return data
@tx1_box.route('/test', methods=["GET"])
def test():
return "test"
print 'test'
print database.get_value()
return "111"
# 给所有用户发送信息
def send_all_data(sv, data):
if sv.users is not None and len ( sv.users ) > 0:
......
#!/usr/bin/evn python
# coding=utf-8
from flask import Blueprint, request
import time,json
import apps.gbvar.dict_properties as dict_p
login = Blueprint('login', __name__)
register = Blueprint('register', __name__)
@login.route('/login',methods=['POST'])
def login1():
data = request.get_data ()
print data
result = {
"user_unid": "tx1_dev_unid", # 必填,用户unid
"user_type": "device", # 可选,用户类型,不出现表示"user",即普通用户。
"atoken": str(time.time()), # 必填,用户的atoken
"atoken_edt": str(time.strftime ( "%Y-%m-%d %H:%M:%S", time.localtime(time.time()))), # 必填,atoken到期时间
"rtoken": str(time.time()), # 可选,用户的rtoken
"rtoken_edt": str(time.strftime ( "%Y-%m-%d %H:%M:%S", time.localtime(time.time()))), # 可选,rtoken到期时间
}
return json.dumps ( result, ensure_ascii=False )
@register.route('/manage/devs/tx1_dev_unid/register',methods=['POST'])
def register1():
data = request.get_data ()
return data
@register.route('/recv_data/http_url',methods=['GET'])
def get_recv_url():
url = 'http://{}:{}/api/v1/tx1_box/events'.format(dict_p.get_value()['tx1_host'],dict_p.get_value()['tx1_http_port'])
print(url)
result = {"http_url": url}
return json.dumps ( result, ensure_ascii=False )
\ No newline at end of file
No preview for this file type
#!/usr/bin/evn python
# coding=utf-8
#存储路径规范
#卡口/任务/日期/小时/分钟
#违法/任务/日期/类型/小时
#事件/任务/日期/类型/小时
#交通参数(流量、密度类)/任务/日期/类型/小时
import time
import datetime
import os
import json
import uuid
import base64
import apps.gbvar.dict_properties as dict_p
class EventToLocalUtil(object):
"""docstring for EventToLocalUtil"""
def __init__(self):
super(EventToLocalUtil, self).__init__()
self.rootPath = ''
def setRootPath(self, rootPath):
self.rootPath = rootPath
self.__loginfo('save_root_path: {}'.format(rootPath))
# return tuple: (bool, picAbsPathList, infoAbsPathList)
# 返回元祖。元素0-是否成功。 1-图片存储绝对路径列表 2-信息存储绝对路径列表(目前一条记录只有一个信息文件)
# @todo 现在只支持base64的图片存储。如果图片是url,还需补充函数功能。
def saveEventToLocal(self, dataDict):
isok = False
outPicsPath = []
outInfoPath = []
beginTime = time.time()
if 'event_type' in dataDict and 'event_cate' in dataDict:
# if 'pics' in dataDict:
basePath = self.generatePath(dataDict)
self.__loginfo('generatePath result:{}'.format(basePath))
if not os.path.exists(basePath):
os.makedirs(basePath)
infoPath = ''
if 'pics' in dataDict:
picsArr = dataDict['pics']
index = 0
for pic in picsArr:
picPath = ''
if 'ofilename' in pic:
if index == 0:
infoPath = (pic['ofilename'].split('.'))[0]
# infoPath = pic['ofilename']
picPath = basePath + '/' + pic['ofilename']
elif 'event_refid' in dataDict:
if(len(dataDict['event_refid'])<=0):
dataDict['event_refid'] = str(uuid.uuid1())
if index == 0:
infoPath = dataDict['event_refid']
picPath = '{}-{}{}'.format(dataDict['event_refid'] , index , '.jpg')
else:
self.__logerror('saveEventToLocal cannot find ofilename or event_refid,\
picPath cannot generate, will not save pic')
if(len(picPath) >0):
if 'pic_base64' in pic:
try:
with open(picPath, 'wb') as f:
f.write(base64.b64decode(pic['pic_base64']))
outPicsPath.append(picPath)
except Exception as e:
self.__logerror('save pic failed, exception:')
self.__logerror(e)
else:
self.__logerror('saveEventToLocal cannot find pic_base64')
self.__logerror(pic)
pic['pic_base64'] = ''
index = index+1
if(len(infoPath)<=0):
if 'event_refid' in dataDict:
if(len(dataDict['event_refid'])<=0):
dataDict['event_refid'] = str(uuid.uuid1())
infoPath = basePath + '/' + dataDict['event_refid'] + '.json'
else:
self.__logerror('saveEventToLocal cannot find event_refid,\
infoPath cannot generate')
else:
infoPath = basePath + '/' + infoPath + '.json'
try:
with open(infoPath, 'w') as f:
json.dump(dataDict, f)
outInfoPath.append(infoPath)
isok = True
except Exception as e:
self.__logerror('save infoPath failed, exception:')
self.__logerror(e)
else:
__logerror("cannot find event_type and event_cate in dataDict")
isok = False
endtime = time.time();
self.__loginfo("saveEventToLocal duration time:{} ms".format( (endtime-beginTime)*1000 ))
return (isok, outPicsPath, outInfoPath)
def utc2local(self, utc_dtm ):
local_tm = datetime.datetime.fromtimestamp( 0 )
utc_tm = datetime.datetime.utcfromtimestamp( 0 )
offset = local_tm - utc_tm
return utc_dtm + offset
# 不同的种类有不同的路径结构。
#存储路径规范
#卡口/任务/日期/小时/分钟
#违法/任务/日期/类型/小时
#事件/任务/日期/类型/小时
#交通参数(流量、密度类)/任务/日期/类型/小时
#判断逻辑,生成路径均在此函数中实现
def generatePath(self, dataDict):
et = datetime.datetime.now()
if 'event_dt' in dataDict:
if 'T' in dataDict['event_dt']:
et = datetime.datetime.strptime(dataDict['event_dt'], "%Y-%m-%dT%H:%M:%S.%f")
et = self.utc2local(et)
pass
else:
et = datetime.datetime.strptime(dataDict['event_dt'], "%Y-%m-%d %H:%M:%S.%f")
et = self.utc2local(et)
pass
else:
self.__loginfo('generatePath cannot find event_dt, use current time')
vid = ''
if 'task_id' in dataDict:
vid = dataDict['task_id']
elif 'vchan_refid' in dataDict:
vid = dataDict['vchan_refid']
else:
vid = 'unkown'
genPath = ''
eventType = dataDict['event_type']
eventCate = dataDict['event_cate']
if eventType == 'vehicle' :
# 卡口
if 'illegal' not in dataDict:
genPath = '%s/kakou/%s/%04d%02d%02d/%02d/%02d'%(self.rootPath,vid,et.year, \
et.month,et.day,et.hour, et.minute)
else:
#违法
genPath = '%s/weifa/%s/%04d%02d%02d/%s/%02d'%(self.rootPath,vid,et.year, \
et.month,et.day,dataDict['event_type'], et.hour)
# 交通参数
elif eventType == 'tflow' \
or eventType == 'pflow' or eventType == 'pdensity':
genPath = '%s/jiaotongcanshu/%s/%04d%02d%02d/%s/%02d'%(self.rootPath,vid,et.year, \
et.month,et.day,dataDict['event_type'], et.hour)
# 事件
elif eventType == 'xcycle' or eventType == 'pedestrian' or eventCate == 'behavior':
genPath = '%s/shijian/%s/%04d%02d%02d/%s/%02d'%(self.rootPath,vid,et.year, \
et.month,et.day,dataDict['event_type'], et.hour)
else:
genPath = '%s/unkown/%s/%04d%02d%02d/%s/%02d'%(self.rootPath,vid,et.year, \
et.month,et.day,dataDict['event_type'], et.hour)
return genPath
def __loginfo(self, logstr):
print('[info][event_to_local]:{}'.format(logstr))
def __logerror(self, logstr):
print('[error][event_to_local]:{}'.format(logstr))
eventToLocal = EventToLocalUtil()
\ No newline at end of file
......@@ -14,6 +14,7 @@ import fdb
import sys
import os
from commons.util import *
import apps.commons.event_to_local as etl
app = Flask(__name__, static_folder='dist')
# 获取本脚本所在的路径
pro_path = os.path.split(os.path.realpath(__file__))[0]
......@@ -29,6 +30,12 @@ app.register_blueprint(task, url_prefix='/api/v1/tx1_box/task')
#注册code路由
app.register_blueprint(code_sev, url_prefix='/api/v1/codes')
#注册login路由
app.register_blueprint(login, url_prefix='/api/v1/auth/users')
#注册register路由
app.register_blueprint(register, url_prefix='/api/v1')
@app.route('/', methods=["GET"])
def index():
return flask.send_file ( "dist/index.html" )
......@@ -57,12 +64,12 @@ def init():
print database.get_value()
'''newLanguages = [
(1, 'Dylan')
(2, 'Dylan3')
]
cur.executeman hjj ( "insert into tb_traffic(id,name) VALUES(?,?)",
newLanguages
)
con.commit ()
con.commit ()'''
sql_select = 'select * from tb_traffic'
# 显示全部内容
......@@ -70,7 +77,7 @@ def init():
print(cur.fetchall ())
cur.close ()
con.close ()'''
con.close ()
####====================database===================
#启动服务
......@@ -80,6 +87,7 @@ if __name__=='__main__':
init()
_h=dictProperties['tx1_host']
_p=int(dictProperties['tx1_ws_port'])
etl.eventToLocal.setRootPath(dictProperties['save_root_path'])
start_ws(_h,_p)
print sv_global.get_value()
t1 = threading.Thread ( target=thread_start, name='start_ws_serv', args={sv_global.get_value (), } )
......
#系统参数
tx1_host=192.168.9.32
tx1_host=192.168.88.159
tx1_http_port=20090
tx1_ws_port=20080
......@@ -17,4 +17,6 @@ task_4=/root/UserApp/vioncfg/Ops/ServerConfig.xml@运维服务@./start.sh
cut_pic_url=http://192.168.88.109:10088/apiv1/capture
#重启任务指令
start_task=./task_start.sh
\ No newline at end of file
start_task=./task_start.sh
save_root_path=./datasave
\ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!