Пример #1
0
    def press_power_key():
        try:
            cmd = 'adb shell input keyevent 26'
            os.system(cmd)

        except Exception, e:
            LogUtil.log_e(e.message)
Пример #2
0
 def process_item(self, host, pagelink, page):
     LogUtil.n("开始解析页面:" + pagelink, self.crystal()._taskId)
     try:
         dom = etree.HTML(page)
         self.collectURLs(dom=dom, pagelink=pagelink, host=host)
     except Exception, e:
         LogUtil.e(traceback.format_exc())
Пример #3
0
    def press_home():
        try:
            cmd = 'adb shell input keyevent 3'
            os.system(cmd)

        except Exception, e:
            LogUtil.log_e(e.message)
Пример #4
0
 def get_flow_data(package_name):
     uid = AdbUtil.get_uid(package_name)
     if uid == 0:
         log.log_i('app uid is 0, check app 是否打开')
         return 0, 0
     cmd = 'cat /proc/net/xt_qtaguid/stats'
     flag_net = AdbUtil.exec_adb_shell(cmd)
     if 'No such file or directory' not in flag_net:
         try:
             cmd = 'cat /proc/net/xt_qtaguid/stats | grep %s' % uid
             str_uid_net_stats = AdbUtil.exec_adb_shell(cmd)
             # 有可能有多行数据
             list_rx = []  # 接收网络数据流量列表
             list_tx = []  # 发送网络数据流量列表
             for item in str_uid_net_stats.splitlines():
                 rx_bytes = item.split()[5]
                 tx_bytes = item.split()[7]
                 list_rx.append(int(rx_bytes))
                 list_tx.append(int(tx_bytes))
             float_total_net_traffic = (sum(list_rx) +
                                        sum(list_tx)) / 1024.0
             float_total_net_traffic = round(float_total_net_traffic, 4)
             return sum(list_rx), sum(list_tx), float_total_net_traffic
         except Exception, e:
             log.log_e('cannot get flow from /proc/net/xt_qtaguid/stats' +
                       e.message)
Пример #5
0
 def tryClick(self, url, start=0):
     if not self.chrome_enable:
         return
     LogUtil.i("start try click")
     try:
         self.driver.get(url)
     except Exception, e:
         LogUtil.e(traceback.format_exc())
Пример #6
0
 def getByChrome(self, url):
     page = ""
     LogUtil.n(str(self.cnt) + ' ' + url)
     self.cnt = self.cnt + 1
     try:
         self.driver.get(url)
     except Exception, e:
         LogUtil.e(traceback.format_exc())
Пример #7
0
 def getByRequests(self, url):
     LogUtil.n(str(self.cnt) + ' ' + url)
     self.cnt = self.cnt + 1
     headers = {
         "user-agent":
         "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0"
     }
     page = requests.get(url, verify=False,
                         headers=headers).content.decode("utf-8")
     return page
Пример #8
0
    def double_click_back():
        try:
            cmd = 'adb shell input keyevent 4'
            i = 0
            while i < 1:
                os.system(cmd)
                i += 1

        except Exception, e:
            LogUtil.log_e(e.message)
Пример #9
0
 def parse_number(self, num_str, power, precision=2):
     divisor=10**power
     try:
         num=int(num_str)
         num=num/divisor
         format_str='%%%d.%df' %(16, precision)
         return format_str %num
     except:
         LogUtil.debug("parse_number(%s,%d,%d)" %(num_str, power, precision))
         return None        
Пример #10
0
 def get_cur_activity():
     try:
         cmd = 'dumpsys activity top | findStr ACTIVITY'
         result = AdbUtil.exec_adb_shell(cmd)
         if result is None or result == '':
             return 'unknow'
         activity_name = result.split('/')[1].strip()
         activity_name = activity_name.split(' ')[0].strip()
         return activity_name
     except Exception, e:
         log.log_e('get current activity failure' + e.message)
         return ''
Пример #11
0
 def get_cur_packagename():
     try:
         cmd = 'dumpsys activity top | findStr ACTIVITY'
         result = AdbUtil.exec_adb_shell(cmd)
         if result is None or result == '':
             return 'unknow'
         package_name = re.findall(r'com.\w+.\w+', result, re.M)
         package_name = package_name[0].strip()
         # result_trs = result.split()
         # activity_name = result_trs[len(result_trs) - 2].split('/')[1]
         return package_name
     except Exception, e:
         log.log_e('get current activity failure' + e.message)
         return ''
Пример #12
0
 def get_battery_data(pkg_name):
     try:
         if pkg_name is None or pkg_name == '':
             cmd = 'dumpsys batterystats'
         else:
             cmd = 'dumpsys batterystats %s' % pkg_name
         # data = subprocess.check_output(cmd, shell=True)
         data = AdbUtil.exec_adb_shell(cmd)
         if data is not None and data is not '':
             return data
         else:
             return 0
     except IOError as e:
         LogUtil.log_e('getbatterydata ' + e.message)
 def get_versioncode(package_name):
     try:
         cmd = 'dumpsys package %s | findStr versionName' % package_name
         process_result = AdbUtil.exec_adb_shell(cmd)
         if process_result is None or process_result == '':
             return '0.0.0.0'
         # 得到的结果格式是: versionName=3.2.13.2303
         results = process_result.strip().split('=')
         # 假如有两个值,我们认为是存活的,一个进程本身,一个push进程(不考虑多个push进程的情况)
         version_code = results[1].strip()
         return version_code
     except Exception as e:
         log.log_e('get process alive failure' + e.message)
         return '0.0.0.0'
Пример #14
0
 def collectURLs(self, dom, pagelink, host):
     LogUtil.n("开始初始化爬出url:" + pagelink, self.crystal()._taskId)
     urls = dom.xpath('//a[not(contains(@href,"javasc"))]/@href')
     for url in urls:
         try:
             url = self.standardizeUrl(host, url)
         except Exception, e:
             LogUtil.e(traceback.format_exc())
             url = False
         if url is not False:
             pattern = re.compile("login|signin|oauth|log-in|sign-in", re.I)
             if pattern.search(url):
                 if (url not in self.bloom):
                     self.bloom.add(url)
                     self.queue.put(url)
                 break
Пример #15
0
 def process_alive(package_name):
     try:
         cmd = 'ps | findStr %s' % package_name
         process_result = AdbUtil.exec_adb_shell(cmd)
         if process_result is None or process_result == '':
             return False
         process_result = process_result.split('\r\n')
         # 假如有两个值,我们认为是存活的,一个进程本身,一个push进程(不考虑多个push进程的情况)
         if len(process_result) > 1:
             return True
         # 判断是否是push进程
         if len(process_result) == 1:
             if package_name + ':' in process_result[0]:
                 return False
         return True
     except Exception as e:
         log.log_e('get process alive failure' + e.message)
Пример #16
0
    def get_package_name_by_uid(uid):
        try:
            cmd = 'adb shell ps | findStr %s' % uid
            results = os.popen(cmd, "r")
            package_name = ''
            while 1:
                line = results.readline()
                if not line: break
                lines = line.split(' ')
                if lines[0] == uid:
                    package_name += lines[len(lines) - 1].strip()
                    package_name += '、'
            package_name_length = len(package_name)
            package_name = package_name[:package_name_length - 3]
            results.close()
            return package_name

        except IOError as e:
            LogUtil.log_e('get packageName by uid' + e.message)
Пример #17
0
 def updateSnapshot(self, snapMessage):
     LogUtil.debug("snap message:"+snapMessage)
     pairs=snapMessage.split(",")
     self.securityID=pairs[3].split("=")[1].strip()
     self.origTime=pairs[0].split("=")[1].strip()
     self.channelNo=pairs[1].split("=")[1].strip()
     self.tradingPhaseCode=pairs[5].split("=")[1].strip()
     self.tradingPhaseCodeDesc=''
     self.prevClosePrice=self.parse_number(pairs[6].split("=")[1].strip(), 4, 3)
     self.numTrades=pairs[7].split("=")[1].strip()
     self.totalVolumeTrade=self.parse_number(pairs[8].split("=")[1].strip(), 2, 2)
     self.totalValueTrade=self.parse_number(pairs[9].split("=")[1].strip(), 4, 3)
     
     index=11
     while index<len(pairs):
         if pairs[index]=='MDEntryType=0 ':  #buy
             priceLevel=int(pairs[index+3].split("=")[1])
             self.buyPrice[priceLevel]=self.parse_number(pairs[index+1].split("=")[1], 6, 3)
             self.buyVolume[priceLevel]=self.parse_number(pairs[index+2].split("=")[1], 2, 2)
             index=index+4
         elif pairs[index]=='MDEntryType=1 ': #sell
             priceLevel=int(pairs[index+3].split("=")[1])
             self.sellPrice[priceLevel]=self.parse_number(pairs[index+1].split("=")[1], 6, 3)
             self.sellVolume[priceLevel]=self.parse_number(pairs[index+2].split("=")[1], 2, 2)
             index=index+4
         elif pairs[index]=='MDEntryType=2 ':   #last
             self.lastPrice=self.parse_number(pairs[index+1].split("=")[1], 6, 3)
             index=index+4
         elif pairs[index]=='MDEntryType=7 ':   #max
             self.maxPrice=self.parse_number(pairs[index+1].split("=")[1], 6, 3)
             index=index+4
         elif pairs[index]=='MDEntryType=8 ':   #min
             self.minPrice=self.parse_number(pairs[index+1].split("=")[1], 6, 3)
             index=index+4
         elif pairs[index]=='MDEntryType=xh':  #nominal
             self.nominalPrice=self.parse_number(pairs[index+1].split("=")[1], 6, 3)
             index=index+4                
         else:
             LogUtil.warning("Unexpected format:index="+str(index)+"str="+pairs[index])
             index=index+1            
Пример #18
0
def check_status(resJson, statusName="status", code="status_code", reason="status_reason"):
    logging = LogUtil().getLogging()
    if (resJson is None):
        logging.info('-------OpenError 1. ---')
        raise OpenError(ResponseCode.sys_error, ResponseCode.sys_error_desc, None)
    res_dic = json.loads(resJson)
    if res_dic.get(statusName) is None:
        logging.info('-------OpenError 2. ---')
        raise OpenError(ResponseCode.sys_error, ResponseCode.sys_error_desc, None)
    status_code = res_dic.get(statusName).get(code)
    status_reason = res_dic.get(statusName).get(reason)
    if 0 != status_code and "0" != status_code:
        logging.info('-------OpenError 3. ---')
        raise OpenError(status_code, status_reason, None)
Пример #19
0
def http_get(url, params={}, header={}):
    logging = LogUtil().getLogging()
    httpUrl = url
    # logging.info('-----------------------')
    # logging.info(httpUrl)
    # logging.info('-----------------------')
    if params is not None and len(params) > 0:
        httpUrl = url + "?" + _encode_params(**params)
    httpUrl = httpUrl.replace(': ', ':')
    httpUrl = httpUrl.replace(', ', ',')
    httpUrl = httpUrl.replace("'", '"')
    logging.info('-----> httpUrl: ' + httpUrl)
    # print httpUrl
    req = urllib2.Request(httpUrl, None, headers=header)
    res = urllib2.urlopen(req)
    body = _read_body(res)
    logging.info('-----> body: ' + body)
    # check_status(body)
    return body
Пример #20
0
 def on_leSecuriyID_returnPressed(self):
     """
     Slot documentation goes here.
     """
     new_security_id=self.leSecurityID.text()
     LogUtil.debug("new Security ID input:"+new_security_id)
     self.leSecurityID.setText("")
     if self.currentSecurityID!=new_security_id:
         LogUtil.debug("current Security:"+self.currentSecurityID+",new id:"+new_security_id)
         self.currentSecurityID=new_security_id
         try:
             hKQuotationSnapshot=self.hKQuotationSnapshotMap[new_security_id]
         except:
             hKQuotationSnapshot=HKQuotationSnapshot()
             hKQuotationSnapshot.securityID=new_security_id
             LogUtil.debug("No existing Quotation:"+new_security_id)
         self.render_quotation(hKQuotationSnapshot)    
Пример #21
0
class Parser:

    _parser = None

    def __init__(self, crystal, proto="https://"):
        self.proto = proto
        self.crystal = weakref.ref(crystal)
        self.queue = crystal._queue
        self.lock = crystal._lock
        self.bloom = crystal._bloom
        if self.queue is None:
            raise QueueNotInit
        if self.bloom is None:
            raise BloomNotInit

    @classmethod
    def getInstance(cls):
        if cls._parser is None:
            cls._parser = Parser()
        return cls._parser

    def setProto(self, proto):
        self.proto = proto

    def setDomain(self, domainFir):
        self.domainFir = domainFir

    def getDomain(self):
        return self.domainFir

    def process_item(self, host, pagelink, page):
        LogUtil.n("开始解析页面:" + pagelink, self.crystal()._taskId)
        try:
            dom = etree.HTML(page)
            self.collectURLs(dom=dom, pagelink=pagelink, host=host)
        except Exception, e:
            LogUtil.e(traceback.format_exc())
        LogUtil.n("该页面收集URL结束:" + pagelink, self.crystal()._taskId)
Пример #22
0
        else:
            try:
                cmd_snd = 'cat /proc/uid_stat/%s/tcp_snd' % uid
                cmd_rec = 'cat /proc/uid_stat/%s/tcp_rcv' % uid
                str_totalTxBytes = AdbUtil.exec_adb_shell(cmd_snd)
                str_totalRxBytes = AdbUtil.exec_adb_shell(cmd_rec)
                if 'No such file or directory' not in str_totalTxBytes and 'No such file or directory' not in str_totalRxBytes:
                    float_total_net_traffic = (
                        int(str_totalRxBytes) +
                        int(str_totalTxBytes)) / 1024.0 / 1024.0
                    float_total_net_traffic = round(float_total_net_traffic, 4)
                    return int(str_totalRxBytes), int(
                        str_totalTxBytes), float_total_net_traffic
            except Exception as e:
                log.log_e(
                    'cannot get flow from /proc/uid_stat/tcp_snd  or tcp_rcv' +
                    e.message)

        return 0, 0, 0

    """
     获取当前Activity的名称
    """

    @staticmethod
    def get_cur_activity():
        try:
            cmd = 'dumpsys activity top | findStr ACTIVITY'
            result = AdbUtil.exec_adb_shell(cmd)
            if result is None or result == '':
                return 'unknow'
Пример #23
0
 def handleQuotationSnapshotUpdated(self, hKQuotationSnapshot):
     #TODO:{Andrew}use lamda to compare value and if not eq, set value & color, else changed color
     security_id=hKQuotationSnapshot.securityID
     LogUtil.debug("handleQuotationSnapshotUpdated security id:"+security_id)
     self.hKQuotationSnapshotMap[security_id]=hKQuotationSnapshot
     self.render_quotation(hKQuotationSnapshot)
Пример #24
0
    def tryClick(self, url, start=0):
        if not self.chrome_enable:
            return
        LogUtil.i("start try click")
        try:
            self.driver.get(url)
        except Exception, e:
            LogUtil.e(traceback.format_exc())
        (targets, length) = self.find_targets()
        for index in range(start, length):
            element = targets[length - 1 - index]
            if (element.is_displayed() and element.is_enabled()):
                try:
                    element.click()
                except Exception, e:
                    LogUtil.e(traceback.format_exc())
                self.driver.get(url)
                (targets, length) = self.find_targets()
        self.driver.quit()
        self.driver = webdriver.Chrome(chrome_options=self.options)
        self.driver.set_page_load_timeout(Downloader.page_load_time)
        self.driver.set_script_timeout(Downloader.script_time)
        self.driver.implicitly_wait(Downloader.max_wait_time)
        LogUtil.i("finish try click")
        return

    def find_targets(self):
        targets = []
        for tagname in self.click_event:
            elements = self.driver.find_elements_by_tag_name(tagname)
            for element in elements:
Пример #25
0
# 主程序运行入口
if __name__ == '__main__':
    # 避免两个模块之间相互引入出现错误

    # 初始化数据源使用的字典
    # 程序中识别名称:创建时使用的源数据名称
    dbLinkName = {
        "crma": "yya",
        "crmb": "yyb",
        "crmc": "yyc",
        "crmd": "yyd",
        "crme": "572_yye_dadb",
        # "pdb": "pdb_larkbird",
        "crmkf": "crmkfdb_prod"
    }
    log = LogUtil()
    # 记录日志
    log.logInsert(jobName='boeCbossOaoJhsbZiyu',
                  taskPos='CBOSS-OAO激活失败自动修改为DF',
                  taskStatus='1',
                  taskLog='开始执行')
    try:
        # 程序开始时间
        startTime = time.time()
        # 创建日志保存工具类

        log.logInsert(jobName='boeCbossOaoJhsbZiyu',
                      taskPos='CBOSS-OAO激活失败自动修改为DF',
                      taskStatus='0',
                      taskLog='开始创建数据源')
        # 备份表所在的数据源
Пример #26
0
    def get_fps_data_by_gfxinfo(pkg_name):

        # 为了验证一帧是否合格
        def validator(x):
            if x is None:
                return False

            xs = x.split('\t')
            # 必须要有三个数值
            if len(xs) < 2 or len(xs) > 5:
                return False

            return True

        # 为了处理通过adb shell dumpsys gfxinfo package_name 获得的结果
        def handle_fps_result(x):
            # 截取 【Profile data in ms:】之后的数据
            first_result = re.findall(r'Profile.*hierarchy', x, re.DOTALL)
            if len(first_result) < 1:
                return None
            activity_name = re.findall(r'(com.*)/.*@', first_result[0])
            data = re.findall(r'Execute(.*?)\r\n\r\n', first_result[0],
                              re.DOTALL)

            if len(data) < 1:
                return None

            if len(data) > 1:
                result = data[1].strip().split('\r\n\t')
            else:
                result = data[0].strip().split('\r\n\t')

            return result

        try:
            cmd = 'dumpsys gfxinfo %s' % pkg_name
            fps_result = AdbUtil.exec_adb_shell(cmd)
            fps_result = handle_fps_result(fps_result)
            if fps_result is None or len(fps_result) < 1:
                return None, None, None
            # 得到的fps_result中是包含\t的。
            frames = [frame for frame in fps_result if validator(frame)]

            frame_count = len(frames)
            jank_count = 0
            vsync_count = 0
            if len(frames) > 0:

                for frame in frames:
                    time_block = frame.strip().split('\t')

                    # 计算一帧渲染的时间
                    render_time = 0
                    try:
                        for i in range(len(time_block)):
                            render_time += float(time_block[i])
                            i += 1
                    except Exception as e:
                        log.log_e('render_time get failure' + e.message)
                    """
                    执行一次命令,总共收集到了m帧(理想情况下m=128),但是这m帧里面有些帧渲染超过了16.67毫秒,算一次jank,一旦jank,
                    需要用掉额外的垂直同步脉冲。其他的就算没有超过16.67,也按一个脉冲时间来算(理想情况下,一个脉冲就可以渲染完一帧)

                    所以FPS的算法可以变为:
                    m / (m + 额外的垂直同步脉冲) * 60
                    """
                    if render_time > 16.67:
                        jank_count += 1
                        if render_time % 16.67 == 0:
                            vsync_count += int(render_time / 16.67) - 1
                        else:
                            vsync_count += int(render_time / 16.67)
                fps = int(frame_count * 60) / (frame_count + vsync_count)

                return frame_count, jank_count, fps
            else:
                # 不滑动,没有帧率数据时返回0,0,0
                return 0, 0, 0
        except Exception as e:
            log.log_e('get fps failure,please check ' + e.message)
Пример #27
0
class Downloader:
    # 1.requests  2.chrome-headless
    _downloader = None
    chrome_enable = False
    page_load_time = 30
    script_time = 30
    max_wait_time = 30
    min_wait_time = 1

    def __init__(self):
        self.options = webdriver.ChromeOptions()
        prefs = {"profile.managed_default_content_settings.images": 2}
        self.options.add_experimental_option("prefs", prefs)
        self.options.binary_location = '/opt/google/chrome-unstable/google-chrome-unstable'
        #self.options.binary_location = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
        self.options.add_argument('headless')
        self.options.add_argument('no-sandbox')
        self.options.add_argument('window-size=1200x600')
        self.options.add_argument('load-images=no')
        self.options.add_argument("--proxy-server=http://127.0.0.1:8000")
        self.options.add_argument(
            '--user-agent="Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0"'
        )
        self.driver = webdriver.Chrome(chrome_options=self.options)
        self.driver.set_page_load_timeout(Downloader.page_load_time)
        self.driver.set_script_timeout(Downloader.script_time)
        self.driver.implicitly_wait(Downloader.max_wait_time)
        self.click_event = ["button"]
        self.cnt = 0

    @classmethod
    def getInstance(cls):
        if cls._downloader is None:
            cls._downloader = Downloader()
        return cls._downloader

    def get(self, url):
        page = ""
        if self.chrome_enable:
            page = self.getByChrome(url)
        else:
            page = self.getByRequests(url)
        return page

    def setChromeEnable(self, enable):
        self.chrome_enable = enable

    # 1.requests
    def getByRequests(self, url):
        LogUtil.n(str(self.cnt) + ' ' + url)
        self.cnt = self.cnt + 1
        headers = {
            "user-agent":
            "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0"
        }
        page = requests.get(url, verify=False,
                            headers=headers).content.decode("utf-8")
        return page

    # 2.chrome-headless
    def getByChrome(self, url):
        page = ""
        LogUtil.n(str(self.cnt) + ' ' + url)
        self.cnt = self.cnt + 1
        try:
            self.driver.get(url)
        except Exception, e:
            LogUtil.e(traceback.format_exc())
        #LogUtil.d(str(self.driver.page_source))
        try:
            page = self.driver.find_elements_by_xpath(
                "/html")[0].get_attribute("innerHTML")
        except Exception, e:
            LogUtil.e(traceback.format_exc())
Пример #28
0
    def run(self):
        self.dialog.pushButtonMsgRecvStart.setEnabled(False)
        self.dialog.pushButtonMsgRecvStop.setEnabled(True)
        
        self.dialog.msgRecvCnt.setText("0")
        self.dialog.msgUpdateTime.setText("0")
        self.dialog.msgStatus.setText("0")
        
        LogUtil.getLoggerInstance(self.config, "msg_recv")
        LogUtil.info("msg_recv:"+" begin")
        
        config=configparser.ConfigParser()
        config.read(self.config)
        
        msg_sub_addr=config.get("msg_recv", "msg_sub_addr")
        msg_sub_topic=config.get("msg_recv", "msg_sub_topic")
        ctx=zmq.Context()
        sock=ctx.socket(zmq.SUB)
        sock.connect(msg_sub_addr)
        sock.setsockopt_string(zmq.SUBSCRIBE, msg_sub_topic)

        host=config.get("reqresp", "host")
        database=config.get("reqresp", "database")
        user=config.get("reqresp","user")
        password=config.get("reqresp", "password")
        
        conn=pgdb.connect(database=database, host=host, user=user, password=password)
        insert_curs=conn.cursor()    
        
        #read trader config
        ApplID           =config.get('trader','ApplID') 
        SubmittingPBUID  =config.get('trader','SubmittingPBUID') 
        SecurityID       =config.get('trader','SecurityID') 
        SecurityIDSource =config.get('trader','SecurityIDSource') 
        OwnerType        =config.get('trader','OwnerType') 
        ClearingFirm     =config.get('trader','ClearingFirm') 
        TransactTime     =config.get('trader','TransactTime') 
        UserInfo         =config.get('trader','UserInfo') 
        ClOrdID          =config.get('trader','ClOrdID') 
        AccountID        =config.get('trader','AccountID') 
        BranchID         =config.get('trader','BranchID') 
        OrderRestrictions=config.get('trader','OrderRestrictions') 
        Side             =config.get('trader','Side') 
        OrdType          =config.get('trader','OrdType') 
        OrderQty         =config.get('trader','OrderQty') 
        Price            =config.get('trader','Price') 
        StopPx           =config.get('trader','StopPx') 
        MinQty           =config.get('trader','MinQty') 
        MaxPriceLevels   =config.get('trader','MaxPriceLevels') 
        TimeInForce      =config.get('trader','TimeInForce') 
        LotType          =config.get('trader','LotType')
        req_num=0
        message_type=106301
        appid=630
        oms_order_id=0
        order_status='0'
        oms_proc_status='0'
        
        insert_req ="""INSERT INTO req_resp ( 
                          message_type,    
                          appid,           
                          oms_order_id,    
                          rept_status,    
                          req_text,        
                          oms_proc_status, 
                          insert_time,
                          src_code) 
         VALUES(%(message_type)s,%(appid)s,%(oms_order_id)s,%(rept_status)s,%(req_text)s,%(oms_proc_status)s,localtimestamp,%(src_code)s)         
        """
        oms_order_id_prex='1000'
        src_code='1000'
        insert_dict={'message_type':0, 'appid':0, 'oms_order_id':'', 'rept_status':'0', 'req_text':'', 'oms_proc_status':'', 'src_code':src_code}
        
        
        msgRecvCnt=0
        msgWriteCnt=0
        msgUpdateTime=None
        msgErrCnt=0
        msgHKRecvCnt=0
        
        
        recvMsgStatus=RecvMsgStatus()
        
        while not self.toStop:
            try:
                (message_type, message_id, src_time, recv_msg)=sock.recv_pyobj()
                msgRecvCnt=msgRecvCnt+1
                recvMsgStatus.msgRecvCnt=str(msgRecvCnt)
                msgUpdateTime=datetime.datetime.now().strftime('%H:%M:%S.%f')
                recvMsgStatus.msgUpdateTime=msgUpdateTime

                if message_type==306311: #hk
                    hKQuotationSnapshot=HKQuotationSnapshot()
                    hKQuotationSnapshot.updateSnapshot(recv_msg)
                    self.quotationUpdated.emit(hKQuotationSnapshot)
                    msgHKRecvCnt=msgHKRecvCnt+1
                    recvMsgStatus.msgHKRecvCnt=str(msgHKRecvCnt)
                    req_num=req_num+1
                    for item in recv_msg.split(','):
                        lines=item.split('=')
                        if lines[0]=='SecurityID':
                            SecurityID=lines[1]
                        if lines[0]=='MDEntryType' and lines[1]=='1':
                            next_is_sell_price=True
                        else:
                            next_is_sell_price=False
                        if lines[0]=='MDEntryPx' and next_is_sell_price:
                            Price=lines[1]
                            break                            
                    
                    ClOrdID=oms_order_id_prex+str(req_num).rjust(6, '0')
                    LogUtil.debug('ClOrdID='+ClOrdID+',req_num='+str(req_num))
                    oms_order_id=ClOrdID
                    
                    req_text='ApplID='+ApplID                         \
                        +',SubmittingPBUID='+SubmittingPBUID     \
                        +',SecurityID='+SecurityID               \
                        +',SecurityIDSource='+SecurityIDSource   \
                        +',OwnerType='+OwnerType                 \
                        +',ClearingFirm='+ClearingFirm           \
                        +',TransactTime='+TransactTime           \
                        +',UserInfo='+UserInfo                   \
                        +',ClOrdID='+ClOrdID                     \
                        +',AccountID='+AccountID                 \
                        +',BranchID='+BranchID                   \
                        +',OrderRestrictions='+OrderRestrictions \
                        +',Side='+Side                           \
                        +',OrdType='+OrdType                     \
                        +',OrderQty='+OrderQty                   \
                        +',Price='+Price                         \
                        +',StopPx='+StopPx                       \
                        +',MinQty='+MinQty                       \
                        +',MaxPriceLevels='+MaxPriceLevels       \
                        +',TimeInForce='+TimeInForce             \
                        +',LotType='+LotType
                    print(req_text)
                    
                    insert_dict['message_type']=106301
                    insert_dict['appid']=630
                    insert_dict['oms_order_id']=oms_order_id
                    insert_dict['rept_status']='0'
                    insert_dict['req_text']=req_text
                    insert_dict['oms_proc_status']='0'
                    insert_dict['src_code']=src_code
                    
                    insert_curs.execute(insert_req,insert_dict)
                    if insert_curs.rowcount!=1:
                        #TODO error handle, rollback?
                        LogUtil.error("no data insert"+req_text)
                    else:
                        conn.commit()

            except Exception as e:
                msgErrCnt=msgErrCnt+1
                recvMsgStatus.msgErrCnt=str(msgErrCnt)
                LogUtil.error(e)
                LogUtil.error("MsgRecvErr:msgErrCnt="+str(msgErrCnt)+",msgRecvCnt="+str(msgRecvCnt)+",msgWriteCnt="+str(msgWriteCnt))
            finally:
                pass
            #TODO    
            
            self.recvStatusUpdated.emit(recvMsgStatus)
            LogUtil.debug("MsgRecvErr:msgErrCnt="+str(msgErrCnt)+",msgRecvCnt="+str(msgRecvCnt)+",msgWriteCnt="+str(msgWriteCnt))
            
        self.dialog.pushButtonMsgRecvStart.setEnabled(True)
        self.dialog.pushButtonMsgRecvStop.setEnabled(False)