task.py 9.29 KB
#!/usr/bin/evn python
# coding=utf-8
from flask import Blueprint, request
import flask
import json,re,time,io
import os
from commons.util import *
import gbvar.ws_serv_global  as sv_global
import gbvar.dict_properties as dict_p
import commons.editXml as editXml
import requests
import re

task = Blueprint('task', __name__)


'''
初始化系统任务
'''
@task.route('',methods=['GET'])
def init_task():
    tasks = []
    list_data = {}

    data1 = make_task_info('task_1');
    tasks.append(data1)

    data2 = make_task_info ( 'task_2' );
    tasks.append ( data2 )

    data3 = make_task_info ( 'task_3' );
    tasks.append ( data3 )

    data4 = make_task_info ( 'task_4' );
    tasks.append ( data4 )

    list_data.setdefault('list_data',tasks)
    res = flask.make_response ( json.dumps(list_data,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

'''
编辑任务
'''
@task.route('/edit/<path:task_index>', methods=["POST","OPTIONS"])
def edit_task_inf(task_index):
    data = request.get_data ()
    print type ( data )
    task_data = json.loads ( data )
    task = dict_p.get_value ()['task_%s' % task_index]
    if task is None or task == '':
        return None
    tasks = re.split ( '[@]', task )
    if len ( tasks ) < 4:
        return None
    mtask_path = tasks[2]
    scen = task_data['mtasks'][0]['scenes'][0]

    '''
          ===========================更改task_name start===============
    '''
    if task_data.has_key('subtask_name'):
        task_name = task_data['subtask_name']
        if task_name is not None:
            task_name_doc = editXml.parseXmlStr ( tasks[0] )
            if task_name_doc:
                root = task_name_doc.documentElement
                Name = root.getElementsByTagName ( "Name" )[0]
                if Name is None or len(Name.childNodes) == 0:
                    newtext = task_name_doc.createTextNode ( task_name )
                    Name.appendChild ( newtext )
                else:
                    Name = Name.childNodes[0]
                    Name.data = task_name
                xml = task_name_doc.toxml ()
                xml = xml.replace ( '<?xml version="1.0" ?>', '<?xml version="1.0"  encoding="GBK"?>' )
                editXml.writeXml ( tasks[0], task_name_doc.toxml () )

    '''
          ======================更改play_url start====================
    '''
    if scen.has_key('play_urls'):
        play_urls = scen['play_urls']
        play_url = play_urls['rtsp']
        if play_url is not None:
            scenes = editXml.parseXmlStr ( os.path.join(tasks[1],'scene.xml') )
            root = scenes.documentElement
            #scen_play_url = root.getElementsByTagName ( "scene1" )[0].getElementsByTagName ( "play_urls" )[0].getElementsByTagName ( "rtsp" )[0].childNodes[0]
            scen_play_url = \
            root.getElementsByTagName ( "scene1" )[0].getElementsByTagName ( "play_urls" )[0].getElementsByTagName (
                "rtsp" )[0]
            print scen_play_url
            if scen_play_url is None or len(scen_play_url.childNodes) == 0:
                newtext = scenes.createTextNode ( play_url )
                scen_play_url.appendChild ( newtext )
            else:
                scen_play_url = scen_play_url.childNodes[0]
                scen_play_url.data = play_url
            xml = scenes.toxml ()
            xml = xml.replace( '&quot;', '"' )
            xml  = xml.replace( '<?xml version="1.0" ?>', '<?xml version="1.0"  encoding="GBK"?>' )
            editXml.writeXml ( os.path.join(tasks[1],'scene.xml'), xml )


    '''
        ==================更改标定  start====================
    '''
    if scen.has_key('calibration'):
        calibration = scen['calibration']
        if calibration.has_key('calibration'):
            cal = calibration['calibration']
            if cal is not None and cal != '':
                editXml.writeXml ( os.path.join(mtask_path,'calibration.xml'), cal )


    '''
        ==================更改参数  start====================
    '''
    if scen.has_key('config'):
        config = scen['config']
        if config is not None and config !='' and config.has_key('xml'):
            xml = config['xml']
            editXml.writeXml ( os.path.join ( mtask_path, 'config.xml' ), xml )

    '''
        ==================更改roi  start=====================
    '''
    if scen.has_key('rois'):
        rois = scen['rois']
        if rois is not None and rois != '':
            roi = rois[0]['roi']
            if roi is not None and roi != '':
                editXml.writeXml ( os.path.join ( mtask_path, 'roi_1.xml' ), roi )

    '''
    启动任务开始
    '''
    os.system('pkill -9 VAServer')

    result_data = {"ecode": "200", "enote": "OK"}
    res = flask.make_response (
        json.dumps ( result_data, 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,HEAD'
    res.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return res


'''
截图
'''
@task.route('/pic_cut/<path:task_id>', methods=["GET"])
def cut_pic(task_id):
    cut_inf = {}
    cut_inf.setdefault('taskid',task_id)
    result = {'ecode':400,'enote':"截图失败!"}
    try:
        r = requests.post ( dict_p.get_value()['cut_pic_url'], json.dumps ( cut_inf ) )
        result = r.json ()
    except Exception as e:
        print e
    res = flask.make_response (json.dumps ( result, ensure_ascii=False ) )
    res.headers['Access-Control-Allow-Origin'] = '*'
    res.headers['Access-Control-Allow-Methods'] = 'POST,GET,OPTIONS,HEAD'
    res.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return res





'''
创建任务详情信息
'''
def make_task_info(task_index):
    print dict_p
    task = dict_p.get_value()[task_index]
    if task is  None or task == '':
        return {}

    tasks = re.split ( '[@]', task )
    if len(tasks) < 4:
        return {}

    task = {}
    task_n = tasks[0]
    task.setdefault('subtask_name',read_task_name(task_n))
    taski = tasks[1]
    task.setdefault ( 'subtask_id', read_task_id (  os.path.join(taski +'task.xml' )))
    mtask_path = tasks[2]
    rtsp = read_rtsp ( os.path.join ( taski, 'scene.xml' ) )
    if rtsp =='' or rtsp is None:
        task.setdefault ( 'is_active', False)
    else:
        task.setdefault ( 'is_active', True )

    task.setdefault('mtasks',make_mtasks(os.path.join(mtask_path,'calibration.xml'),os.path.join(mtask_path,'roi_1.xml'),tasks[3],os.path.join(mtask_path,'config.xml'),  rtsp))
    return task

def read_task_name(xmlPath):
    task_name_doc = editXml.parseXmlStr( xmlPath )
    if task_name_doc:
        root = task_name_doc.documentElement
        name = root.getElementsByTagName ( "Name" )[0]
        if name is not None and len(name.childNodes) > 0:
            name = name.childNodes[0]
            print 'name =%s' % name.data
            return name.data
    return ''

def read_task_id(xmlPath):
    task_id_doc = editXml.parseXmlStr ( xmlPath )
    if task_id_doc:
        root = task_id_doc.documentElement
        task_id = root.getElementsByTagName ( "task_unid" )[0]
        if task_id is not None and len(task_id.childNodes) > 0:
            task_id = task_id.childNodes[0]
            print 'task_id =%s' % task_id.data
            return task_id.data
    return ''

def read_rtsp(xmlPath):
    scenes = editXml.parseXmlStr ( xmlPath )
    if scenes:
        root = scenes.documentElement
        scen_play_url = \
        root.getElementsByTagName ( "scene1" )[0].getElementsByTagName ( "play_urls" )[0].getElementsByTagName (
            "rtsp" )[0]
        if scen_play_url is not None and len(scen_play_url.childNodes) > 0:
            scen_play_url = scen_play_url.childNodes[0]
            return scen_play_url.data
    return ''

def make_mtasks(cal_path,roi_path,basconpath,conpath,rtsp):
    mtasks = []
    scenes = []
    cal =  editXml.openXml( cal_path )
    cal = cal.replace('\n','')
    calibration = {}
    calibration.setdefault('calibration',cal)

    con  = editXml.openXml( conpath )
    con = con.replace ( '\n', '' )
    config = {}
    config.setdefault('xml',con)

    play_urls = {}
    play_urls.setdefault('rtsp',rtsp)

    bascon = editXml.openXml( basconpath )
    bascon = bascon.replace( '\n', '' )
    basConfig = {}
    basConfig.setdefault('xml',bascon)

    rois = []
    roi = editXml.openXml( roi_path )
    ro = {}
    ro.setdefault('roi',roi)
    rois.append(ro);

    sce = {}
    sce.setdefault('calibration',calibration)
    sce.setdefault('rois',rois)
    sce.setdefault ( 'config', config )
    sce.setdefault ( 'basicConfig', basConfig )
    sce.setdefault ( 'play_urls', play_urls )
    sce.setdefault('algo_type',0)
    scenes.append(sce)

    mtask = {}
    mtask.setdefault('scenes',scenes)
    mtasks.append(mtask)
    return mtasks