http_serv.py 6.63 KB
#!/usr/bin/evn python
# coding=utf-8
from flask import Blueprint,request,redirect,url_for
import flask
#from werkzeug import secure_filename
import requests,json,re,time,io
import sys
import os
import uuid
from commons.util import *
import gbvar.ws_serv_global  as sv_global
import gbvar.database_global as database
import gbvar.dict_properties as dict_p
from threading import Thread
#配置文件路径
pro_path = "/root/UserApp/apps"
con_path = '/'.join((pro_path, 'special.properties'))
print  con_path
dictProperties=Properties(con_path).getProperties()
import commons.editXml as editXml
import commons.event_to_local as etl
import dao.firebird_dao as dbmanipulation
import commons.data_process as proc
import gbvar.ws_global as global_ws_list
import gbvar.ws_list as wsdic
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

tx1_box = Blueprint('tx1_box', __name__)
#数据接收接口
@tx1_box.route('/events', methods=["POST"])
def dataRecv():

    data = request.get_data()
    dataDic = json.loads(data)
    if type(dataDic) is dict:
        subtask_id = None
        if dataDic.has_key ( 'subtask_id' ):
            subtask_id = dataDic['subtask_id']
            # recvThird(dataDic)
            t = Thread(target=recvThird, args=(dataDic,))
            t.start()
        print "subtask=%s" % subtask_id
        try:
            res = etl.eventToLocal.saveEventToLocal ( dataDic )
            print res
            #print type(res)
            outPicsPath = res[2]
            print outPicsPath
            
            pics = dataDic['pics']
            index = 0
            for pic in pics:
                del pic['pic_base64']
                pic_src = outPicsPath[index]
                #pic_src = pic_src[pic_src.find ( 'data' ) + 4:len ( pic_src )]
                print pic_src
                # pic['src_url'] = dict_p.get_value()['pic_url'] % pic_src
                pic['src_url'] = "http://%s:20070/%s" % (wsdic.get_host_ip(), pic_src)
                index = index + 1
            
            #pic_src = outPicsPath[0]
            #print "pics=%s" % pic_src
            #pic_src = pic_src[pic_src.find('data')+4:len(pic_src)]
            #print pic_src
            #del dataDic['pics'][0]['pic_base64']
            #dataDic['pics'][0]['src_url'] = dict_p.get_value()['pic_url'] % pic_src

            send_by_ws ( json.dumps(dataDic), subtask_id )
            print(res)
        except Exception, a:
            print a
            pass
        #存入本地数据库
        # save_alarm_data(data,res)
    else:
        print('error: data to dict failed, data:{}'.format(data))

    return json.dumps({"ecode":200,"enote":'ok'})

@tx1_box.route('/events/list', methods=["GET"])
def getEventList():
    save_alarm_data('','')
    return ''
    # arguments = request.args()
    # for item in arguments:
    #     print(item)
    # sql = 'select * from TB_TRAFFIC_EVENT  ROWS 1 TO 19'
    #
    # eventResult = dbmanipulation.selectDb(sql)
    # print 'test'
    # # print database.get_value()
    # res = flask.make_response(json.dumps(eventResult, encoding="UTF-8", ensure_ascii=False, sort_keys=False, indent=4).encode('utf-8'))
    # res.headers['Access-Control-Allow-Origin'] = '*'
    # res.headers['Access-Control-Allow-Methods'] = 'POST,GET,OPTIONS'
    # res.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    # return res

def send_by_ws(data,subtask_id):
    for unid, ws in wsdic.getAllWs().iteritems ():
        old_task_id = wsdic.get_task_by_unid ( unid )
        print "old_task_id=%s" % old_task_id
        if ws and old_task_id == subtask_id:
            ws.send(data)
# 给所有用户发送信息
def send_all_data(sv, data):
     if sv.users is not None and len ( sv.users ) > 0:
         for addr in sv.users:
             print ('addr=%s' % addr)
             sv.send_data (data, addr )


#系统初始化:读取配置文件获取初始化任务列表
def get_task_info():
    dictProperties = dict_p.get_value()
    result_list = []
    if dictProperties:
        for i in range(4):
            result_data = {}
            task_id = 'task_%s' % i
            ds = dictProperties[task_id]
            if ds.find ( "@" ) != -1:
                task_inf = re.split ( '[@]', ds )
                result_data.setdefault ( "task_id",i+1 )
                result_data.setdefault ( "task_name", task_inf[1] )
                result_data.setdefault ( "task_info", readerXml(task_inf[0]) )
                result_list.append ( result_data )
            else:
                continue
    return json.dumps ( result_list, ensure_ascii=False )

# 初始化报警数据
def save_alarm_data(adata, src):
    setting = ''
    with open("text", 'r') as f:
        setting = json.loads(f.read())
    data = setting
    dataType = data['event_type']

    proc.dataProcess.initData(data)

    trffic_data = proc.dataProcess.trffic_data()
    dbmanipulation.save_trrfic_Db(trffic_data)

    if (dataType == 'vehicle' or dataType == 'xcycle' or dataType == 'pedestrian'):
        if (data.has_key('driver')):
            if(data['driver'].has_key('face')):
                face_data = proc.dataProcess.face_data()
                dbmanipulation.save_face_Db(face_data)
        else:
            return '人脸不存在'
    elif (dataType == 'pflow' or dataType == 'tflow' or dataType == 'pdensity'):
        flow_data = proc.dataProcess.flow_data()
        dbmanipulation.save_flow_data_Db(flow_data)
        flow_event = proc.dataProcess.flow_event()
        dbmanipulation.save_flow_event_Db(flow_event)

#初始化任务详情信息:包含algo_args信息、calibration标定参数信息以及roi信息的组合
def creat_mtasks():

    '''任务配置参数'''
    mtasks = []
    '''场景'''
    scenes = []
    '''标定信息'''
    callibration = {}
    '''rois信息'''
    rois = []
    '''最新设置的算法配置参数'''
    config = {}
    '''basicConfig系统默认算法参数'''
    basicConfig = {}
    '''play_urls待分析的原始视频源的输入地址'''
    play_urls = {}
    return mtasks
#读取任务信息参数
def readerXml(file_path):
    return editXml.readerXml ( file_path )

@tx1_box.route('/pic_cut', methods=["POST"])
def post_test():
    data_1 = request.get_data ()
    print data_1
    data = {}
    data.setdefault('pic_base64','123123123123123123123123')
    return json.dumps ( data, ensure_ascii=False )
headers = {
"Content-Type":"application/json"
}
def recvThird(rdata):
    url = dictProperties["third_party_url"]
    if url:
        try:
            # r = requests.post(url,rdata, timeout=20)
            r = requests.post(url=url,data=json.dumps(rdata),headers=headers)
            print r
        except Exception as e:
            print "发送失败: err: " + str(e)