TMenu.py 124 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547
  1. # -*- coding:utf-8 -*-
  2. from ssat_sdk.utils.LoggingUtil import printLog
  3. from ssat_sdk.utils.string_util import getDigitFromString
  4. from ssat_sdk.device_manage.capturecard_manager import CCardManager
  5. from ssat_sdk.MenuTree3.TExcelParser import CExcelParser
  6. from ssat_sdk.MenuTree3.UIT_runner import UITRunner
  7. from ssat_sdk import getMenuTree3SelectedProjectCfgPath, OCRConvert, getSATTmpDIR, ImageCMP, \
  8. getMenuTree3SelectedPExcelPath, getMenuTree3SelectedTvExcelPath
  9. from ssat_sdk.MenuTree3.TFocus import TFocus
  10. from ssat_sdk.MenuTree3.TConfig import TConfig
  11. from ssat_sdk.MenuTree3.TSourceImpl import TSourceImpl
  12. from ssat_sdk.tv_operator import *
  13. import json
  14. import time
  15. import cv2 as cv
  16. from ssat_sdk.utils.string_util import strcmp
  17. from ssat_sdk.picture.DoubleImage import DoubleImage
  18. from ssat_sdk.source_input import SourceGenInput
  19. g_level = ['First', 'Second', 'Third', 'Fourth', 'Fifth', 'Sixth', 'Seventh', 'Eighth', 'Ninth', 'Tenth', 'Eleventh',
  20. 'Twelfth']
  21. class CTMenu():
  22. # def __init__(self, ocrDict={"lan": "CHN_ENG", "type": 10000}):
  23. def __init__(self, ocrDict=[{"lan": "ChinesePRC+English", "type": 4}, {"lan": "ChinesePRC+English", "type": 253},
  24. {"lan": "ChinesePRC+English", "type": 10001}]):
  25. self.uitRunner = UITRunner()
  26. self.uitPathManage = self.uitRunner.uitPathManage
  27. # 创建视频采集对象
  28. self.ccard = CCardManager()
  29. # 创建OCR对象
  30. self.ocr = OCRConvert()
  31. # 图片切割对象
  32. self.imgCMP = ImageCMP()
  33. # 读取excel并解析出内容;
  34. # 红老鼠遥控对象;
  35. self.redRat3 = TvOperator()
  36. # 配置文件;
  37. self.tconfig = self.uitRunner.uitData.tConfig
  38. self.icon_shape = [1920, 1080]
  39. if self.tconfig.has_option('Screen', 'shape'):
  40. self.icon_shape = self.tconfig.get_value_dict('Screen', 'shape')
  41. # 截图,获取分辨率;
  42. self.Screen = [1920, 1080]
  43. pic = self.getCurrentUIPath()
  44. if os.path.exists(pic) is True:
  45. img = cv.imread(pic)
  46. if img is not None:
  47. self.Screen = [img.shape[1], img.shape[0]]
  48. # 创建获取聚焦区域对象
  49. self.tFocus = TFocus(getMenuTree3SelectedProjectCfgPath(), self.uitRunner, self.Screen, self.icon_shape)
  50. self.ocrDict = ocrDict
  51. # 某数据是否读取过;
  52. self.got_dict = {}
  53. # 22293
  54. self.sourceInput = SourceGenInput()
  55. self.tSource = TSourceImpl(self.ocr, self.ccard, self.redRat3, self.tFocus, self.tconfig, self.uitRunner)
  56. def currentTime(self):
  57. return time.strftime('_%Y-%m-%d_%H_%M_%S', time.localtime(time.time()))
  58. '''
  59. 对应OptionConfig中的getThresholdDict和__getICONConfig
  60. '''
  61. def get_ocr_list(self, level, option):
  62. # OCR识别参数字典 默认值为:百度中英文免费类型
  63. ini_path = os.path.join(getMenuTree3SelectedProjectCfgPath(), "menutree.ini")
  64. if os.path.exists(ini_path) is True:
  65. tconfig = self.uitRunner.uitData.tConfig
  66. # if tconfig.has_option(level, parent + u'.ocr'):
  67. # self.ocrDict = tconfig.get_dict(tconfig.get_value(level, parent + u'.ocr'))
  68. # return
  69. result, path = self.uitRunner.uitData.UITree.get_option(option)
  70. print u"get_ocr_list, path:",path
  71. if result:
  72. # 从当前层逐层往上遍历,寻找ocr参数列表
  73. for i in range(g_level.index(level), -1, -1):
  74. cur_parent = path['parent']
  75. first_parent = path['first_parent']
  76. i_level = g_level[i]
  77. if tconfig.has_option(i_level, option + u'.ocr'):
  78. self.ocrDict = tconfig.get_dict(tconfig.get_value(i_level, option + u'.ocr'))
  79. printLog("TMenu.get_ocr_list:", "Get ocr list by: %s.ocr"%option)
  80. break
  81. elif tconfig.has_option(i_level, cur_parent + u'.ocr'):
  82. self.ocrDict = tconfig.get_dict(tconfig.get_value(i_level, cur_parent + u'.ocr'))
  83. printLog("TMenu.get_ocr_list:", "Get ocr list by: %s.ocr"%cur_parent)
  84. break
  85. elif tconfig.has_option(i_level, first_parent + u'.ocr'):
  86. self.ocrDict = tconfig.get_dict(tconfig.get_value(i_level, first_parent + u'.ocr'))
  87. printLog("TMenu.get_ocr_list:", "Get ocr list by: %s.ocr"%first_parent)
  88. break
  89. else:
  90. # 如果没有,使用默认;
  91. self.ocrDict = [{"lan": "ChinesePRC+English", "type": 4}, {"lan": "ChinesePRC+English", "type": 253},
  92. {"lan": "ChinesePRC+English", "type": 10001}]
  93. printLog("TMenu.get_ocr_list:", "Get ocr list fail!!!Using default list!!!")
  94. printLog("TMenu.get_ocr_list:", "Present ocr list:%s"%self.ocrDict)
  95. # 截图并返回当前截图路径
  96. def getCurrentUIPath(self):
  97. current_uiPic = os.path.join(getSATTmpDIR(), "menutree_runpath.png")
  98. self.ccard.takePicture(current_uiPic)
  99. return current_uiPic
  100. def getFocusTextBox3(self, cur_option, focus_box, is_value_sheet=False):
  101. resutl, opcfg = self.tFocus.getOptionConfig(cur_option, is_value_sheet)
  102. dcfg = opcfg['dcfg']
  103. icon_path = opcfg['icon_path']
  104. icon_dir_path = opcfg['dir_path']
  105. if resutl is False or os.path.exists(icon_dir_path) is False:
  106. print u'getFocusTextBox:current use dir_path=%s is null' % (
  107. icon_dir_path)
  108. return focus_box
  109. if icon_dir_path in self.got_dict:
  110. x, y = focus_box[0] - self.got_dict[icon_dir_path]['ref_box'][0], focus_box[1] - \
  111. self.got_dict[icon_dir_path]['ref_box'][1]
  112. return [x, y, x + self.got_dict[icon_dir_path]['width'], y + self.got_dict[icon_dir_path]['height']]
  113. else:
  114. if os.path.exists(icon_dir_path) is True:
  115. # 读取例图,宽高;
  116. img = cv.imread(icon_dir_path)
  117. # 在例图中查找轮廓;
  118. result, box = self.tFocus.findRectByIcon2(icon_dir_path, cur_option, is_value_sheet)
  119. if result is True:
  120. self.got_dict[icon_dir_path] = {"ref_box": box, "width": img.shape[1], "height": img.shape[0]}
  121. x, y = focus_box[0] - box[0], focus_box[1] - box[1]
  122. return [x, y, x + img.shape[1], y + img.shape[0]]
  123. # endif
  124. # endif
  125. # 如果没有字段原样返回;
  126. return focus_box
  127. def getFocusTextBox4(self, icon_dir_path, cur_option, focus_box, is_value_sheet=False):
  128. if os.path.exists(icon_dir_path) is False:
  129. print u'getFocusTextBox:current use dir_path=%s is null' % (
  130. icon_dir_path)
  131. return focus_box
  132. if icon_dir_path in self.got_dict:
  133. x, y = focus_box[0] - self.got_dict[icon_dir_path]['ref_box'][0], focus_box[1] - \
  134. self.got_dict[icon_dir_path]['ref_box'][1]
  135. return [x, y, x + self.got_dict[icon_dir_path]['width'], y + self.got_dict[icon_dir_path]['height']]
  136. else:
  137. if os.path.exists(icon_dir_path) is True:
  138. # 读取例图,宽高;
  139. img = cv.imread(icon_dir_path)
  140. # 在例图中查找轮廓;
  141. result, box = self.tFocus.findRectByIcon2(icon_dir_path, cur_option, is_value_sheet)
  142. if result is True:
  143. self.got_dict[icon_dir_path] = {"ref_box": box, "width": img.shape[1], "height": img.shape[0]}
  144. x, y = focus_box[0] - box[0], focus_box[1] - box[1]
  145. return [x, y, x + img.shape[1], y + img.shape[0]]
  146. # endif
  147. # endif
  148. # 如果没有字段原样返回;
  149. return focus_box
  150. # 获取焦点框文本;
  151. def getFocusText(self, level, first_parent, paths, src_pic, focus_box, is_for_value=False):
  152. # 是否有文字方向字段存在在ini里,如果有则转换文本框坐标;
  153. text_pic = os.path.join(getSATTmpDIR(), "meuttree_area_text.png")
  154. contourRect = self.getFocusTextBox3(paths['option'], focus_box, is_for_value)
  155. self.imgCMP.saveCropPic(src_pic, text_pic, (contourRect[0], contourRect[1], contourRect[2], contourRect[3]))
  156. # 获取ocr_list;
  157. cur_parent, cur_option = paths['parent'], paths['option']
  158. ocr_list = self.uitRunner.uitData.UITree.get_ocr_list(level, cur_parent, cur_option,
  159. True if cur_parent == cur_option else False)
  160. print u"%s,%s,%s =>ocr_list=%s" % (level, cur_parent, cur_option, str(ocr_list))
  161. # 遍历ocr类型;
  162. found = False
  163. ocr_str = ''
  164. # 获取ocr列表;
  165. self.get_ocr_list(level, cur_option)
  166. for item in self.ocrDict:
  167. # 识别ocr;
  168. thresholdDict = self.tconfig.getThresholdDict(first_parent)
  169. ocr_str = self.ocr.getStrWithImgProcess(text_pic, thresholdDict, item["lan"], item["type"], reconTimes=1)
  170. printLog(u"OCR识别的类型字典:%s" % str(item))
  171. printLog(u"OCR识别出的ocr_str为:%s" % str(ocr_str))
  172. # print(u"getCurrentFocusTextEx.ocr_str land = %s, type =%d, ocr_str=%s:"%(item["lan"], item["type"], ocr_str.encode('GB18030')))
  173. ocr_str = unicode(ocr_str).lower()
  174. if is_for_value:
  175. parent_ocr_dict = self.uitRunner.uitData.UITree.get_parent_ocr_dict(cur_parent, value_sheet=True)
  176. else:
  177. parent_ocr_dict = self.uitRunner.uitData.UITree.get_parent_ocr_dict(cur_option)
  178. print u"getCurrentFocusTextEx.parent_ocr_dict:", parent_ocr_dict
  179. list_parent_ocr_value = list(parent_ocr_dict.keys())
  180. print u"getCurrentFocusTextEx.list_parent_ocr_value:", list_parent_ocr_value
  181. current_parent_ocr_value = ""
  182. for parent_ocr_value in list_parent_ocr_value:
  183. parent_ocr_value = str(parent_ocr_value).lower()
  184. if parent_ocr_value in ocr_str or parent_ocr_value == ocr_str:
  185. current_parent_ocr_value = parent_ocr_value
  186. break
  187. try:
  188. curentOption = parent_ocr_dict[current_parent_ocr_value]
  189. except Exception, e:
  190. curentOption = ""
  191. printLog(u"OCR识别出的current_parent_ocr_value为:%s" % str(current_parent_ocr_value))
  192. printLog(u"OCR识别出的curentOCROption为:%s" % str(curentOption))
  193. # printLog(u"传入的目标option为:%s" % str(option))
  194. # 通过OCR来反向识别判断当前识别的option是否为传入的option
  195. if str(curentOption).lower() != "" and str(curentOption).lower() != str(cur_option).lower():
  196. # print "非焦点框=%s" % (ocr_str)
  197. printLog(u"非焦点框=%s" % str(ocr_str))
  198. return 0, ocr_str
  199. # 再遍历目标焦点ocr;
  200. for std_str in paths["option_for_ocr"]:
  201. std_str = str(std_str).lower()
  202. # print 'std_str:', std_str, type(std_str)
  203. # print 'ocr_str:', ocr_str, type(ocr_str)
  204. if std_str in ocr_str or std_str == ocr_str:
  205. found = True
  206. break
  207. # endfor
  208. if found is True:
  209. break
  210. # endfor
  211. return found, ocr_str
  212. # 获取焦点框轮廓;
  213. def getFocusBox_temp(self, level, first_parent, option=''):
  214. # 焦点框截图;
  215. bx_pic = ''
  216. # 当前截图;
  217. cur_img = self.getCurrentUIPath()
  218. # 查找焦点框轮廓;
  219. bx_found, bx_focus = self.tFocus.findRectByIcon(cur_img, level, first_parent, option)
  220. printLog("getCurrentFocusBox(%d,%s):" % (int(bx_found), str(bx_focus)))
  221. if bx_found is True:
  222. # 保存焦点框截图;
  223. bx_pic = os.path.join(getSATTmpDIR(), "menutree_focus_area" + str(time.time()) + ".png")
  224. self.imgCMP.saveCropPic(cur_img, bx_pic, (bx_focus[0], bx_focus[1], bx_focus[2], bx_focus[3]))
  225. # 返回结果;
  226. return bx_found, bx_focus, bx_pic
  227. # 获取焦点框滚动文本;
  228. def getMarqueeText(self, level, first_parent, option=''):
  229. # 获取焦点框信息;
  230. bx_found, bx_focus, bx_pic = self.getFocusBox_temp(level, first_parent, option)
  231. if bx_found is False:
  232. printLog("getMarqueeText=>焦点框识别失败")
  233. return False, ''
  234. # 按要求,跑马灯只需要百度高精度;
  235. orc_type = {"lan": "ChinesePRC+English", "type": 253}
  236. # ocr识别;
  237. thresholdDict = self.tconfig.getThresholdDict(first_parent)
  238. # ocr_result = self.ocr.getStr(bx_pic, orc_type["lan"], orc_type["type"])
  239. ocr_result = self.ocr.getStrWithImgProcess(bx_pic, thresholdDict, orc_type["lan"], orc_type["type"],
  240. reconTimes=1)
  241. if ocr_result == "ERR<Exp>" or ocr_result.__len__() == 0:
  242. printLog("getMarqueeText=>ocr识别失败=%s" % (ocr_result))
  243. return False, ocr_result
  244. # 返回结果;
  245. return True, ocr_result
  246. def getOCRStrListByOptionList(self, optionList):
  247. OCRStrList = []
  248. for option in optionList:
  249. hasOption, optionDict = self.uitRunner.uitData.UITree.get_option(option)
  250. if hasOption:
  251. optionStrList = optionDict["option_ocr"]
  252. OCRStrList.extend(optionStrList)
  253. return OCRStrList
  254. def getOCRStrDictByOptionList(self, optionList):
  255. OCRStrDict = {}
  256. for option in optionList:
  257. hasOption, optionDict = self.uitRunner.uitData.UITree.get_option(option)
  258. if hasOption:
  259. optionStrList = optionDict["option_ocr"]
  260. OCRStrDict[option] = optionStrList
  261. return OCRStrDict
  262. def getFocusBoxMarqueeText(self, marquee_dict, level, first_parent, paths):
  263. # 截图2次,判断是否是跑马菜单;
  264. # 第一次;
  265. bx_found, bx_focus, bx_pic1 = self.getFocusBox_temp(level, first_parent, paths['option'])
  266. if bx_found is False:
  267. printLog("getFocusBoxMarqueeText:焦点框识别失败1")
  268. return -1, ''
  269. # 等待1秒后截图;
  270. time.sleep(marquee_dict['sleep_time'])
  271. # 发送鲜活键;
  272. self.redRat3.sendKey(marquee_dict['alive_key'], 1, 0.1)
  273. # 第二次;
  274. bx_found, bx_focus, bx_pic2 = self.getFocusBox_temp(level, first_parent, paths['option'])
  275. if bx_found is False:
  276. printLog("getFocusBoxMarqueeText:焦点框识别失败2")
  277. return -1, ''
  278. # 二图ocr文本是否相似,如果相似认为不是滚动文本;#如果网络问题;
  279. thresholdDict = self.tconfig.getThresholdDict(first_parent)
  280. # ocr_result_text1 = self.ocr.getStr(bx_pic1, "ChinesePRC+English", 253)
  281. ocr_result_text1 = self.ocr.getStrWithImgProcess(bx_pic1, thresholdDict, "CHN_ENG", 10000,
  282. reconTimes=1)
  283. # 发送鲜活键;
  284. self.redRat3.sendKey(marquee_dict['alive_key'], 1, 0.1)
  285. # ocr_result_text2 = self.ocr.getStr(bx_pic2, "ChinesePRC+English", 253)
  286. ocr_result_text2 = self.ocr.getStrWithImgProcess(bx_pic2, thresholdDict, "CHN_ENG", 10000,
  287. reconTimes=1)
  288. # 发送鲜活键;
  289. self.redRat3.sendKey(marquee_dict['alive_key'], 1, 0.1)
  290. # 对比结果:相等非滚动文本,否则视为滚动文本;
  291. if ocr_result_text1 != "" and ocr_result_text1 == ocr_result_text2:
  292. return self.getCurrentFocusTextEx(level, first_parent, paths['parent'], paths['option'],
  293. paths['option_for_ocr'])
  294. else:
  295. destOption = paths['option']
  296. menuList = marquee_dict["menu"]
  297. # 如果只有一项跑马灯,且目标option亦在跑马灯列表中,则直接返回成功结果
  298. if menuList.__len__() == 1 and (destOption in menuList):
  299. return 1, destOption
  300. list_img = []
  301. result = False
  302. ocr_result_text = ''
  303. ocr_text_list = []
  304. # 截图5次;
  305. for i in range(0, 5):
  306. bx_found, bx_focus, bx_pic = self.getFocusBox_temp(level, first_parent, paths['option'])
  307. if bx_found is True:
  308. list_img.append(bx_pic)
  309. # 间隔多久截图;
  310. time.sleep(marquee_dict['sleep_time'])
  311. # 发送鲜活键;
  312. self.redRat3.sendKey(marquee_dict['alive_key'], 1, 0.1)
  313. # endfor
  314. # 遍历文本list_img;
  315. # 按要求,跑马灯只用百度识别;
  316. orc_type = {"lan": "ChinesePRC+English", "type": 10000}
  317. for bx_pic in list_img:
  318. # ocr识别;
  319. # ocr_result_text = self.ocr.getStr(bx_pic, orc_type["lan"], orc_type["type"])
  320. ocr_result_text = self.ocr.getStrWithImgProcess(bx_pic, thresholdDict, orc_type["lan"],
  321. orc_type["type"],
  322. reconTimes=1)
  323. # 识别一次,发送一次鲜活键;
  324. self.redRat3.sendKey(marquee_dict['alive_key'], 1, 0.1)
  325. if ocr_result_text == "ERR<Exp>" and ocr_result_text.__len__() == 0:
  326. return 0, ocr_result_text
  327. ocr_text_list.append(ocr_result_text)
  328. #end for
  329. # 处理识别到的ocr列表:有部分聚焦状态会将option及其值一起包括其中,所以要把相同的部分(option或者值)去掉
  330. ocr_text_list = self.removeDuplicateString(ocr_text_list)
  331. # 获取到跑马灯option的ocr字典
  332. ocrStrDict = self.getOCRStrDictByOptionList(menuList)
  333. print u"获取到的跑马灯Option对应的ocr字典ocrStrDict:", ocrStrDict
  334. print u"识别到的跑马灯ocr文字列表ocr_text_list:",ocr_text_list
  335. for marquee_option in ocrStrDict:
  336. option_ocr_list = ocrStrDict[marquee_option]
  337. for option_ocr in option_ocr_list:
  338. # 一共5张截图,只要有3张满足条件,就算找到了该option(规避同时存在两条相似的跑马灯选项问题,以及跑马灯头尾同时显示的问题)
  339. count = 0
  340. for ocr_text in ocr_text_list:
  341. if ocr_text.lower() in option_ocr:
  342. count += 1
  343. if count >= 3 and destOption == marquee_option:
  344. return 1, destOption
  345. elif count >= 3:
  346. printLog(u"当前聚焦的跑马灯Option实际为:%s"%marquee_option)
  347. return 0, marquee_option
  348. else:
  349. printLog(u"未能识别到当前聚焦的跑马灯Option!!!")
  350. return 0, "unknown marquee text"
  351. def strSplit(self, str):
  352. ret = []
  353. str_int = ''
  354. str_ch = ''
  355. ch_last = ' '
  356. for ch in str:
  357. if ord(ch) > 47 and ord(ch) < 58:
  358. str_int += ch
  359. if str_ch.__len__():
  360. ret.append(str_ch)
  361. str_ch = ''
  362. else:
  363. if ord(ch_last) > 47 and ord(ch_last) < 58 and ch == '.':
  364. str_int += ch
  365. if str_ch.__len__():
  366. ret.append(str_ch)
  367. str_ch = ''
  368. else:
  369. str_ch += ch
  370. if str_int.__len__():
  371. ret.append(str_int)
  372. str_int = ''
  373. ch_last = ch
  374. if str_ch.__len__():
  375. ret.append(str_ch)
  376. if str_int.__len__():
  377. ret.append(str_int)
  378. return ret
  379. def getCurrentFocusOcr_Int(self, icon_level, first_parent, option="", isForValue=False):
  380. print u"getCurrentFocusOcr_Int Start>>>", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
  381. # 聚集框识别;
  382. cur_img = self.getCurrentUIPath()
  383. print u"isForValue:", isForValue
  384. if isForValue:
  385. bxfound, cur_box = self.tFocus.findRectByIcon2(cur_img, option, True)
  386. else:
  387. bxfound, cur_box = self.tFocus.findRectByIcon2(cur_img, option)
  388. # print "getCurrentFocusBox(%d,%s):" % (int(bxfound), str(cur_box))
  389. printLog("getCurrentFocusBox(%d,%s):" % (int(bxfound), str(cur_box)))
  390. if not bxfound or cur_box == []:
  391. return False, "", 0
  392. cur_box = self.getFocusTextBox3(option, cur_box, True)
  393. printLog("getCurrentFocusBox(%d,%s):" % (int(bxfound), str(cur_box)))
  394. # 截图文本框;
  395. txt_pic = os.path.join(getSATTmpDIR(), "meuttree_area_text.png")
  396. self.imgCMP.saveCropPic(cur_img, txt_pic, (cur_box[0], cur_box[1], cur_box[2], cur_box[3]))
  397. # ocr识别;
  398. ocr_result = ''
  399. # 获取ocr列表;
  400. hasOption, path = self.uitRunner.uitData.UITree.get_option(option)
  401. if hasOption:
  402. self.get_ocr_list(path['level'], option)
  403. for orc_item in self.ocrDict:
  404. thresholdDict = self.tconfig.getThresholdDict(first_parent)
  405. # ocr_result = self.ocr.getStr(txt_pic, orc_item["lan"], orc_item["type"])
  406. ocr_result = self.ocr.getStrWithImgProcess(txt_pic, thresholdDict, orc_item["lan"], orc_item["type"],
  407. reconTimes=1)
  408. # print("getCurrentFocusOcr_Int=ocr识别结果=%s" % (ocr_result))
  409. printLog("getCurrentFocusOcr_Int=ocr识别结果=%s" % (ocr_result))
  410. if ocr_result == "ERR<Exp>" or ocr_result.__len__() == 0:
  411. continue
  412. # 字符串去掉末尾">"符号;
  413. ocr_result = ocr_result.strip('>')
  414. # 按数字分解多组文本;
  415. # list_orc = getDigitFromString(ocr_result)
  416. list_ocr = self.strSplit(ocr_result)
  417. # 只判断最后一位是否是数字;
  418. if list_ocr.__len__() < 1:
  419. errorPngName = "menutree_error_" + self.currentTime() + "ocr.png"
  420. error_uiPic = os.path.join(getSATTmpDIR(), errorPngName)
  421. self.ccard.takePicture(error_uiPic)
  422. # print u"当前识别的ocr 不包含int类型值,截图为:%s" % (str(ocr_result))
  423. printLog(u"当前识别的ocr 不包含int类型值,截图为:%s" % (str(ocr_result)))
  424. continue
  425. try:
  426. # 获取最右边的文本,如果是数字则退出;
  427. text_int_str = list_ocr[list_ocr.__len__() - 1]
  428. # print 'text_int_str:', text_int_str
  429. printLog('text_int_str:%s' % str(text_int_str))
  430. text_num = float(text_int_str)
  431. # 返回结果;
  432. return True, ocr_result, text_num
  433. except Exception:
  434. continue
  435. # endfor
  436. print u"getCurrentFocusOcr_Int End<<<", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
  437. return False, "", 0
  438. # 遍历获取ocr结果;
  439. def getCurrentFocusTextEx(self, level, first_parent, cur_parent, option, list_str, isSource=False,
  440. isForValue=False):
  441. print level, first_parent, cur_parent, option
  442. current_uiPic = self.getCurrentUIPath()
  443. if isForValue:
  444. # cur_parent 对应value表里的option;
  445. # option_info = self.xlsparser.get_option(cur_parent)
  446. isFind, contourRect = self.tFocus.findRectByIcon2(current_uiPic, cur_parent, isForValue)
  447. else:
  448. isFind, contourRect = self.tFocus.findRectByIcon2(current_uiPic, option)
  449. printLog(u"获取当前聚焦效果isFind:%s 聚焦区域contourRect:%s" % (str(isFind), str(contourRect)))
  450. if not isFind or contourRect == []:
  451. return -1, ""
  452. else:
  453. found, ocr_str = False, ''
  454. # tmpPic = os.path.join(getSATTmpDIR(), "meuttree_area_text11.png")
  455. # self.imgCMP.saveCropPic(current_uiPic, tmpPic,
  456. # (contourRect[0], contourRect[1], contourRect[2], contourRect[3]))
  457. # 是否有文字方向字段存在在ini里,如果有则转换文本框坐标;
  458. tmpPic = os.path.join(getSATTmpDIR(), "meuttree_area_text.png")
  459. if isForValue:
  460. contourRect = self.getFocusTextBox3(cur_parent, contourRect, True)
  461. else:
  462. contourRect = self.getFocusTextBox3(option, contourRect)
  463. self.imgCMP.saveCropPic(current_uiPic, tmpPic,
  464. (contourRect[0], contourRect[1], contourRect[2], contourRect[3]))
  465. if isSource:
  466. self.redRat3.sendKey("ok")
  467. # print "self.ocrDict:", self.ocrDict
  468. # 获取ocr_list;
  469. ocr_list = self.uitRunner.uitData.UITree.get_ocr_list(level, cur_parent, option, True if cur_parent == option else False)
  470. print u"%s,%s,%s =>ocr_list=%s" % (level, cur_parent, option, str(ocr_list))
  471. # 获取ocr列表;
  472. self.get_ocr_list(level, option)
  473. # 遍历ocr类型;
  474. for item in self.ocrDict:
  475. # 识别ocr;
  476. thresholdDict = self.tconfig.getThresholdDict(first_parent)
  477. ocr_str = self.ocr.getStrWithImgProcess(tmpPic, thresholdDict, item["lan"], item["type"], reconTimes=1)
  478. # print "\n\ngetCurrentFocusTextEx ==========================:OCR-Type=%s, OCR-Text=%s\n\n" % (
  479. # str(item), str(ocr_str))
  480. printLog(u"OCR识别的类型字典:%s" % str(item))
  481. printLog(u"OCR识别出的ocr_str为:%s" % str(ocr_str))
  482. # print(u"getCurrentFocusTextEx.ocr_str land = %s, type =%d, ocr_str=%s:"%(item["lan"], item["type"], ocr_str.encode('GB18030')))
  483. ocr_str = unicode(ocr_str).lower()
  484. if isSource is False:
  485. if isForValue:
  486. parent_ocr_dict = self.uitRunner.uitData.UITree.get_parent_ocr_dict(cur_parent, value_sheet=True)
  487. else:
  488. parent_ocr_dict = self.uitRunner.uitData.UITree.get_parent_ocr_dict(option)
  489. print u"getCurrentFocusTextEx.parent_ocr_dict:", parent_ocr_dict
  490. list_parent_ocr_value = list(parent_ocr_dict.keys())
  491. print u"getCurrentFocusTextEx.list_parent_ocr_value:", list_parent_ocr_value
  492. # 比较所有的ocr
  493. for parent_ocr_value in list_parent_ocr_value:
  494. parent_ocr_value = str(parent_ocr_value).lower()
  495. if parent_ocr_value in ocr_str or strcmp(parent_ocr_value, ocr_str):
  496. # 优先比较目标option,如果符合要求则直接返回找到结果
  497. for std_str in list_str:
  498. std_str = str(std_str).lower()
  499. if strcmp(std_str, parent_ocr_value):
  500. printLog(u"传入的目标Value_ocr_list为:%s" % list_str)
  501. printLog(u"与目标option的ocr_value:%s相同"%std_str)
  502. return 1, option
  503. else:
  504. # 否则则识别出该ocr_value所对应的option
  505. try:
  506. currentOption = parent_ocr_dict[parent_ocr_value]
  507. except Exception,e:
  508. currentOption = ""
  509. printLog(u"识别出的currentOption为:%s" % currentOption)
  510. if currentOption != "":
  511. return 0, currentOption
  512. else:
  513. if isSource is True:
  514. # 如果是信源 而且识别出是非目标信源则跳出该语言
  515. for ocr_std_str_list in ocr_list:
  516. # print "ocr_std_str_list:",ocr_std_str_list
  517. for ocr_std_str in ocr_std_str_list:
  518. # print "ocr_std_str:",ocr_std_str
  519. ocr_std_str = str(ocr_std_str).lower()
  520. # print 'ocr_std_str:', ocr_std_str, type(ocr_std_str)
  521. # print 'ocr_str:', ocr_str, type(ocr_str)
  522. if ocr_std_str in ocr_str or ocr_std_str == ocr_str:
  523. printLog(u"非焦点信源=%s" % str(ocr_str))
  524. return 0, ocr_str
  525. else:
  526. # 全部ocr_value都不符合要求,则视为menutree中不存在此option相关的数据
  527. printLog(u"未能识别出当前Option!!!请检查Mnenutree相关参数配置!!!")
  528. return 0, ocr_str
  529. # 移动到目标网格焦点上;
  530. def move2TargetGridNode(self, level, first_parent, paths, returnKeyEventCount, Max_Try=15):
  531. result = False
  532. cur_option = paths['option']
  533. last_box, cur_box = [], []
  534. # 遍历正序;
  535. is_positive = True
  536. key_idx = False
  537. key_dir = ['right', 'left']
  538. # 第一个,最后一个;
  539. is_first, is_last = False, False
  540. # 上一行,下一行;
  541. is_up, is_down = False, False
  542. # 获取等待时间
  543. waitTime = self.getOptionWaitTime(paths['option'])
  544. time.sleep(waitTime)
  545. while True:
  546. cur_pic = self.getCurrentUIPath()
  547. found_box, cur_box = self.tFocus.findRectByIcon2(cur_pic, cur_option)
  548. if found_box is True:
  549. if last_box == cur_box:
  550. if is_positive is True: # 正序;
  551. if is_last is True:
  552. is_positive = False
  553. key_idx = not key_idx
  554. last_box = []
  555. # 移动上一格;
  556. self.redRat3.sendKey(key_dir[int(key_idx)])
  557. continue
  558. if is_down is False:
  559. is_down = True
  560. # 移动下一行;
  561. self.redRat3.sendKey('down')
  562. key_idx = not key_idx
  563. else:
  564. is_last = True
  565. key_idx = not key_idx
  566. else: # 逆序;
  567. if is_first is True:
  568. break
  569. if is_up is False:
  570. is_up = True
  571. # 移动上一行;
  572. self.redRat3.sendKey('up')
  573. key_idx = not key_idx
  574. else:
  575. is_first = True
  576. key_idx = not key_idx
  577. # endif
  578. else:
  579. found_target, cur_text = self.getFocusText(level, first_parent, paths, cur_pic, cur_box)
  580. if found_target is True:
  581. result = True
  582. break
  583. # 保留为上一焦点框;
  584. last_box = cur_box
  585. # 移动下一焦点;
  586. self.redRat3.sendKey(key_dir[int(key_idx)])
  587. # 第一个,最后一个;
  588. is_first, is_last = False, False
  589. # 上一行,下一行;
  590. is_up, is_down = False, False
  591. # endif
  592. else:
  593. printLog(u"网格焦点框识别失败")
  594. break
  595. # endif
  596. # 返回结果;
  597. return result
  598. def move2TargetGridNode_matchTemp(self, level, first_parent, paths, returnKeyEventCount, Max_Try = 15):
  599. # 目标结点;
  600. tgt_option = paths['option']
  601. temp_dir = os.path.join(getMenuTree3SelectedProjectCfgPath(), "match_temp", paths['parent'])
  602. # 选中时的模板
  603. img_focus_temp = os.path.join(temp_dir, tgt_option + '_focus.jpg')
  604. # 未选中模板图
  605. img_unfocus_temp = os.path.join(temp_dir, tgt_option + '_unfocus.jpg')
  606. # 获取等待时间
  607. waitTime = self.getOptionWaitTime(paths['option'])
  608. time.sleep(waitTime)
  609. # 尝试次数;
  610. page_try_time = 15
  611. focus_try_time = 100
  612. # 目标聚集结果;
  613. tgt_focus_result = False
  614. while tgt_focus_result is False:
  615. # 电视截图(原图);
  616. img_tv = self.getCurrentUIPath()
  617. # 查找聚集框是否在目标上;
  618. match_result = self.tFocus.feature_detect.matchSingleImage(img_tv, None, img_focus_temp)
  619. if match_result is not None:
  620. tgt_focus_result = True
  621. break
  622. #end-if
  623. # 查找非聚集目标;
  624. match_result = self.tFocus.feature_detect.matchSingleImage(img_tv, None, img_unfocus_temp)
  625. if match_result is None:
  626. # 尝试次数使用完;
  627. if page_try_time == 0:
  628. break
  629. # 没找到,可能在别的页面,向右移动;
  630. self.redRat3.sendKey('right')
  631. page_try_time = page_try_time - 1
  632. continue
  633. # end-if
  634. print u'匹配度=', match_result['tmpVal']
  635. # 找到非聚集目标后,再查找当前聚集框坐标;
  636. bfound_box, focus_box = self.tFocus.findRectByIcon2(img_tv, tgt_option, is_value_sheet=False) # 不支持叶结点;
  637. if bfound_box is False:
  638. printLog("move2TargetGridNode_matchTemp:未找到聚集框")
  639. break
  640. #end-if
  641. box1, box2 = focus_box, match_result['coordinate']
  642. # 计算非聚集模板与聚集框的位置;
  643. dir = self.tFocus.feature_detect.getOrientationEx(box1, box2)
  644. if dir == -1:
  645. break
  646. # 中心点坐标;center point
  647. # cpt1 = [box1[2]-box1[0],box1[3]-box1[1]]
  648. # cpt2 = [box2[2]-box2[0],box2[3]-box2[1]]
  649. if dir == 0:# 左上方;
  650. self.redRat3.sendKey('right')
  651. elif dir == 1:# 正上方;
  652. self.redRat3.sendKey('down')
  653. elif dir == 2:# 右上方;
  654. self.redRat3.sendKey('left')
  655. elif dir == 3:# 正左方;
  656. self.redRat3.sendKey('right')
  657. elif dir == 4:# 正右方;
  658. self.redRat3.sendKey('left')
  659. elif dir == 5:# 左下方;
  660. self.redRat3.sendKey('right')
  661. elif dir == 6:# 正下方;
  662. self.redRat3.sendKey('up')
  663. elif dir == 7:# 右下方;
  664. self.redRat3.sendKey('left')
  665. # 移动次数用完;
  666. focus_try_time = focus_try_time -1
  667. if focus_try_time == 0:
  668. break
  669. #end-while;
  670. return tgt_focus_result
  671. # 移动到目标节点上;
  672. def move2TargetNode(self, level, first_parent, paths, returnKeyEventCount, findDirection="down", Max_Try=15):
  673. # 按照传入的方向寻找Max_Try次,如果仍未聚焦到option_for_ocr所在的区域,则按照传入方向的反方向 反向寻找 Max_Try 次
  674. # 正向寻找的次数计数和最大次数
  675. count = 0
  676. parent = paths['parent']
  677. option_list = self.uitRunner.uitData.UITree.getSubOptionList(parent)
  678. if option_list.__len__() != 0:
  679. Max_Try = option_list.__len__()
  680. print u"move2TargetNode.%s option_list:"%parent, option_list
  681. # 反向寻找的次数计数和最大次数
  682. Reversecount = 0
  683. Reverse_Max_Try = Max_Try
  684. print u"move2TargetNode:Max_Try:%s, Reverse_Max_Try:%s"%(Max_Try, Reverse_Max_Try)
  685. if findDirection == "grid":
  686. temp_dir = os.path.join(getMenuTree3SelectedProjectCfgPath(), "match_temp", paths['parent'])
  687. if os.path.exists(temp_dir):
  688. return self.move2TargetGridNode_matchTemp(level, first_parent, paths, returnKeyEventCount, Max_Try)
  689. else:
  690. return self.move2TargetGridNode(level, first_parent, paths, returnKeyEventCount, Max_Try)
  691. # 记录上一个焦点识别的文字内容 用于判断是否到达列表的边界 如果到达边界则反向寻找
  692. old_text = "init_old_text"
  693. # 反向寻找的遥控器按键值
  694. findReverseDirection = "up"
  695. if findDirection == "up":
  696. findReverseDirection = "down"
  697. if findDirection == "down":
  698. findReverseDirection = "up"
  699. if findDirection == "left":
  700. findReverseDirection = "right"
  701. if findDirection == "right":
  702. findReverseDirection = "left"
  703. print u"findDirection:", findDirection, type(findDirection)
  704. print u"findReverseDirection:", findReverseDirection, type(findReverseDirection)
  705. # # 去除大小写的识别字符
  706. # option_for_ocr_low = str(option_for_ocr).lower()
  707. isMarquee = False
  708. marquee_dict = {}
  709. # 是否有跑马灯文本;
  710. if paths["others"].__len__():
  711. data_other = json.loads(paths["others"])
  712. if "marquee" in data_other:
  713. marquee_dict = data_other['marquee']
  714. isMarquee = True
  715. # 获取等待时间
  716. waitTime = self.getOptionWaitTime(paths['option'])
  717. printLog(u"move2TargetNode:获取到进入option_%s,等待时间为%s"%(paths['option'],waitTime))
  718. time.sleep(waitTime)
  719. while (True):
  720. print "count:", count
  721. if count >= Max_Try and Reversecount >= Reverse_Max_Try:
  722. break
  723. if isMarquee is True:
  724. isFind, text = self.getFocusBoxMarqueeText(marquee_dict, level, first_parent, paths)
  725. else:
  726. isFind, text = self.getCurrentFocusTextEx(level, first_parent, paths["parent"], paths["option"],
  727. paths["option_for_ocr"])
  728. if isFind == -1:
  729. errorPngName = "menutree_error_" + str(paths["option"]) + self.currentTime() + ".png"
  730. error_uiPic = os.path.join(getSATTmpDIR(), errorPngName)
  731. self.ccard.takePicture(error_uiPic)
  732. printLog(u"聚焦到目标option:%s失败!当前界面无法找到焦点区域!!!出错界面截图%s" % (str(paths["option"]), str(error_uiPic)))
  733. self.redRat3.sendKey("return", returnKeyEventCount, 0.5)
  734. return False
  735. # elif (self.ocr.cmpOcrStr(text, option_for_ocr)):
  736. # 由比较目标文本和识别文本 是否相等 改为 识别文本是否包含目标文本
  737. else:
  738. if isFind == 1:
  739. printLog(u"聚焦到目标option:%s成功!" % str(paths["option"]))
  740. return True
  741. # 判断两次识别的text是否相等来判断是否到达边界
  742. print u"move2TargetNode.text",text
  743. print u"move2TargetNode.old_text",old_text
  744. if self.ocr.cmpOcrStr(text, old_text):
  745. # 如果已经到达边界则不再正方向寻找焦点
  746. count = Max_Try
  747. old_text = "init_old_text"
  748. else:
  749. old_text = text
  750. if count < Max_Try:
  751. count = count + 1
  752. self.redRat3.sendKey(findDirection)
  753. else:
  754. Reversecount = Reversecount + 1
  755. self.redRat3.sendKey(findReverseDirection)
  756. errorPngName = "menutree_error_" + str(paths["option"]) + self.currentTime() + ".png"
  757. error_uiPic = os.path.join(getSATTmpDIR(), errorPngName)
  758. self.ccard.takePicture(error_uiPic)
  759. printLog(u"聚焦到目标option:%s失败!正向遍历%s次,和反向遍历%s次都没有聚焦到option:%s中,截图路径:%s" % (str(paths["option"]),
  760. str(Max_Try), str(Reverse_Max_Try),
  761. str(paths["option"]),
  762. str(error_uiPic)))
  763. return False
  764. # 设置叶子节点值;
  765. def setLeafNodeValue(self, level, first_parent, option, value_excel, value_for_ocr, value, move_key, enter_key,
  766. Max_Try=15):
  767. # 按照传入的方向寻找Max_Try次,如果仍未聚焦到option_for_ocr所在的区域,则按照传入方向的反方向 反向寻找 2*Max_Try 次
  768. # 正向寻找的次数计数和最大次数
  769. count = 0
  770. Max_Try = Max_Try
  771. # 反向寻找的次数计数和最大次数
  772. Reversecount = 0
  773. Reverse_Max_Try = Max_Try * 2
  774. # 记录上一个焦点识别的文字内容 用于判断是否到达列表的边界 如果到达边界则反向寻找
  775. old_text = "init_old_text"
  776. # 正向寻找的遥控器按键值
  777. findDirection = move_key[1] # 向右或者向下
  778. # 反向寻找的遥控器按键值
  779. findReverseDirection = move_key[0] # 向左或者向上
  780. # 获取等待时间
  781. waitTime = self.getLeafWaitTime(option)
  782. printLog(u"setLeafNodeValue:获取到进入叶节点%s,等待时间为%s"%(option, waitTime))
  783. time.sleep(waitTime)
  784. duration = 0.2
  785. isMarquee = False
  786. marquee_dict = {}
  787. leaf_data = self.uitRunner.uitData.UITree.get_value(option)
  788. if leaf_data["others"].__len__():
  789. data_other = json.loads(leaf_data["others"])
  790. # 是否有跑马灯文本;
  791. if "marquee" in data_other:
  792. marquee_dict = data_other['marquee']
  793. isMarquee = True
  794. # 是否有按键时间设置
  795. if "duration" in data_other:
  796. duration = float(data_other['duration'])
  797. printLog(u"读取到的设值间隔为%s"%duration)
  798. value_for_ocr_low = str(value_for_ocr[0]).lower()
  799. # 判断设置值的类型 是rang类型还是str类型
  800. if "range(" in value_for_ocr_low:
  801. isRangeType = True
  802. str_num = value_for_ocr_low.replace("range", "")
  803. list_num = eval(str_num)
  804. min_num = list_num[0]
  805. max_num = list_num[1]
  806. try:
  807. value_num = int(value)
  808. except Exception:
  809. printLog(u"传入的值value:%s和option:%s对应的类型不匹配 !" % (str(value), str(option)))
  810. return False
  811. else:
  812. isRangeType = False
  813. if isRangeType:
  814. # 设置数值范围类型的处理
  815. pass
  816. while (True):
  817. # 执行超过3次操作仍然失败则返回False
  818. if count > 3:
  819. break
  820. isFind, text, text_num = self.getCurrentFocusOcr_Int(level, first_parent, option=option,
  821. isForValue=True)
  822. if not isFind:
  823. errorPngName = "menutree_error_" + str(option) + str(value_excel) + self.currentTime() + ".png"
  824. error_uiPic = os.path.join(getSATTmpDIR(), errorPngName)
  825. self.ccard.takePicture(error_uiPic)
  826. printLog(u"设置叶子节点值时,当前界面无法找到焦点区域!!!getCurrentFocusOcr_Int出错界面截图%s" % str(error_uiPic))
  827. return False
  828. else:
  829. if text_num < min_num or text_num > max_num:
  830. errorPngName = "menutree_error_" + str(option) + '_' + str(
  831. value_excel) + self.currentTime() + ".png"
  832. error_uiPic = os.path.join(getSATTmpDIR(), errorPngName)
  833. self.ccard.takePicture(error_uiPic)
  834. printLog(u"设置叶子节点值时,当前option:%s 识别出来的值text:%s 不在value_for_ocr:%s范围内,截图为:%s" % (
  835. str(option), str(text), str(value_for_ocr), str(error_uiPic)))
  836. return False
  837. # if abs(text_num) == abs(value_num):
  838. if text_num == value_num:
  839. printLog(u"聚焦到目标option:%s,设置value:%s选项成功!" % (str(option), str(value_excel)))
  840. # 聚焦成功发送enter_key
  841. if enter_key != 'default':
  842. self.redRat3.sendKey(enter_key)
  843. return True
  844. else:
  845. if findDirection == 'input':
  846. # 发送按键;
  847. for key in list(str(value_num)):
  848. self.redRat3.sendKey(key, 1, duration)
  849. if max_num > 100:
  850. return True
  851. else:
  852. count = count + 1
  853. # 如果目标值大于现有值,则按正方向按键(向下或者向右)增加当前界面的值
  854. if value_num > text_num:
  855. self.redRat3.sendKey(findDirection, value_num - text_num, duration)
  856. # 如果目标值小于现有值,则按反方向按键(向上或者向左)减少当前界面的值
  857. if value_num < text_num:
  858. self.redRat3.sendKey(findReverseDirection, text_num - value_num, duration)
  859. errorPngName = "menutree_error_" + str(option) + '_' + str(value_excel) + self.currentTime() + ".png"
  860. error_uiPic = os.path.join(getSATTmpDIR(), errorPngName)
  861. self.ccard.takePicture(error_uiPic)
  862. printLog(u"设置叶子节点值时,当前option:%s 设置3次仍未设置到目标值value:%s,截图为:%s " % (str(option), str(value), str(error_uiPic)))
  863. return False
  864. else:
  865. # 设置选项类型的处理
  866. while (True):
  867. print "count:", count
  868. if count >= Max_Try and Reversecount >= Reverse_Max_Try:
  869. break
  870. if isMarquee is True:
  871. # 跑马灯函数需要cur_parent的参数,把cur_parent参数加入到leaf_data中再传进去
  872. result, paths = self.uitRunner.uitData.UITree.get_option(option)
  873. leaf_data['parent'] = paths['parent']
  874. leaf_data['option_for_ocr'] = leaf_data['value_for_ocr']
  875. isFind, text = self.getFocusBoxMarqueeText(marquee_dict, level, first_parent, leaf_data)
  876. else:
  877. isFind, text = self.getCurrentFocusTextEx(level, first_parent, option, value_excel, value_for_ocr,
  878. isForValue=True)
  879. if isFind == -1:
  880. errorPngName = "menutree_error_" + str(option) + '_' + str(
  881. value_excel) + self.currentTime() + ".png"
  882. error_uiPic = os.path.join(getSATTmpDIR(), errorPngName)
  883. self.ccard.takePicture(error_uiPic)
  884. printLog(u"设置叶子节点值时,当前界面无法找到焦点区域!!!getCurrentFocusTextEx 出错界面截图%s" % str(error_uiPic))
  885. return False
  886. # elif (self.ocr.cmpOcrStr(text, value_for_ocr)):
  887. # 由比较目标文本和识别文本 是否相等 改为 识别文本是否包含目标文本
  888. else:
  889. if isFind == 1:
  890. printLog(u"聚焦到目标option:%s,设置value:%s选项成功!" % (str(option), str(value_excel)))
  891. # 聚焦成功发送enter_key
  892. if enter_key != 'default':
  893. self.redRat3.sendKey(enter_key)
  894. return True
  895. # 判断两次识别
  896. # 判断两次识别的text是否相等来判断是否到达边界
  897. if self.ocr.cmpOcrStr(text, old_text):
  898. # 如果已经到达边界则不再正方向寻找焦点
  899. count = Max_Try
  900. old_text = "init_old_text"
  901. else:
  902. old_text = text
  903. if count < Max_Try:
  904. count = count + 1
  905. self.redRat3.sendKey(findDirection)
  906. else:
  907. Reversecount = Reversecount + 1
  908. self.redRat3.sendKey(findReverseDirection)
  909. errorPngName = "menutree_error_" + str(option) + '_' + str(value_excel) + self.currentTime() + ".png"
  910. error_uiPic = os.path.join(getSATTmpDIR(), errorPngName)
  911. self.ccard.takePicture(error_uiPic)
  912. printLog(u"设置叶子节点值时,正向遍历%s次,和反向遍历%s次都没有聚焦到option:%s的value:%s选项中,截图为%s" % (
  913. str(Max_Try), str(Reverse_Max_Try), str(option), str(value_excel), str(error_uiPic)))
  914. return False
  915. return True
  916. # 处理others字段;
  917. def dealOthers(self, level, path):
  918. others = json.loads(path['others'])
  919. if "password" in others:
  920. password = self.tconfig.get_value("Password", others["password"])
  921. # 发送密码前,停2秒(因为像6586机芯响应很慢,密码框还没弹出就完成了密码输入的操作);
  922. time.sleep(2)
  923. # 发送按键;
  924. for key in list(password):
  925. self.redRat3.sendKey(key, 1, 0.2)
  926. time.sleep(1)
  927. # 发送ok键;
  928. if others["enter_key"] != "default":
  929. self.redRat3.sendKey(others["enter_key"])
  930. # 判断是否成功输入密码;
  931. current_uiPic = self.getCurrentUIPath()
  932. # 此处findRectByIcon参数3传递的不是first_parent,而是当前option的parent;
  933. isFind, contourRect = self.tFocus.findRectByIcon(current_uiPic, level, path['parent'])
  934. return not isFind
  935. return False
  936. # 由于测试开始之前都切到黑屏背景,去掉聚焦效果OCR验证,3次焦点验证,验证到有聚焦效果就返回
  937. def isFirstOptionShow(self, level, first_parent, first_option):
  938. for i in range(3):
  939. current_uiPic = self.getCurrentUIPath()
  940. isFind, contourRect = self.tFocus.findRectByIcon2(current_uiPic, first_option)
  941. if isFind:
  942. return True
  943. return False
  944. # 对外接口:设置操作值;
  945. def setOptionValue(self, option, value, Max_Try=15, reTryTime=0, leafNodeValueWaitTime=0.0, returnKeyEventTimes=-1):
  946. # 切黑场;
  947. self.sourceInput.setPattern(11)
  948. printLog(u"开始执行setOptionValue。option:%s value:%s" % (str(option), str(value)))
  949. # 寻路结果;
  950. result = False
  951. # 获取menu path;
  952. value_params, path_params = self.uitPathManage.get_menu_paths(option, value)
  953. printLog(u"获取到达option:%s的路径字典path_params:%s" % (str(option), str(path_params)))
  954. printLog(u"获取设置value:%s的值字典value_params:%s" % (str(value), str(value_params)))
  955. checkRunOptionPathResult = self.uitPathManage.checkRunOptionPath(path_params)
  956. if str(checkRunOptionPathResult) == "NoExit":
  957. printLog(u"表格中不存在到达Option: %s 的路径,在表格中排查到达该Option路径" % str(option))
  958. return False
  959. if str(checkRunOptionPathResult) == "Fail":
  960. printLog(u"表格中到达Option: %s 的路径出现数据断层找不到First层级,在表格中排查到达该Option路径" % str(option))
  961. return False
  962. # returnKeyEventCount = path_params.__len__() + 1
  963. returnKeyEventCount = 0
  964. print u"returnKeyEventCount:", returnKeyEventCount
  965. # 逆序路径key;
  966. revpp = reversed(path_params)
  967. # 根节点是否已进入;
  968. entry = False
  969. first_parent = u''
  970. first_option = u''
  971. # 遍历路径(已排序,从first开始);
  972. # print "revpp:", revpp
  973. for level in revpp:
  974. # print "level:", level, path_params[level]
  975. printLog(u"执行路径level:%s 对应路径字典:%s" % (str(level), str(path_params[level])))
  976. # 是否进入根结点;
  977. if entry == False:
  978. # 标记已进入根;
  979. entry = True
  980. first_parent = path_params[level]["parent"]
  981. first_option = path_params[level]["option"]
  982. checkFirstOptionTimes = 0
  983. while True:
  984. if checkFirstOptionTimes > 2:
  985. errorPngName = "menutree_error_" + str(option) + '_' + str(value) + self.currentTime() + ".png"
  986. error_uiPic = os.path.join(getSATTmpDIR(), errorPngName)
  987. self.ccard.takePicture(error_uiPic)
  988. printLog(u"执行setOptionValue ERROR!option:%s value:%s ;尝试3次快捷按键仍然没有唤出聚焦焦点界面!!! 出错截图:%s" % (
  989. str(option), str(value), str(error_uiPic)))
  990. return False
  991. printLog(u"第%s次尝试呼出一级界面" % str(checkFirstOptionTimes))
  992. # 判断是否存在others字段,others字段中存在first_key,则优先使用first_key进入
  993. try:
  994. others = json.loads(path_params[level]["others"])
  995. except Exception,e:
  996. others = {}
  997. printLog("section others:%s"%others)
  998. if "first_key" in others.keys():
  999. first_key = others["first_key"]
  1000. else:
  1001. first_key = path_params[level]["parent"]
  1002. printLog(u"进入根节点,first_key:%s"%first_key)
  1003. # 进入根节点
  1004. self.redRat3.sendKey(first_key)
  1005. waitTime = self.getParentWaitTime(path_params[level]["parent"])
  1006. printLog(u"打开%s界面的等待时间waittime为:%s" % (str(path_params[level]["parent"]), str(waitTime)))
  1007. time.sleep(waitTime)
  1008. # 获取ocr列表;
  1009. self.get_ocr_list(level, option)
  1010. if self.isFirstOptionShow(level, first_parent, first_option):
  1011. printLog(u"呼出一级菜单界面")
  1012. break
  1013. else:
  1014. time.sleep(5)
  1015. self.redRat3.sendKey("return", 1)
  1016. checkFirstOptionTimes = checkFirstOptionTimes + 1
  1017. # 如果一级界面弹出成功,则退出时候返回按键次数加1
  1018. returnKeyEventCount = returnKeyEventCount + 1
  1019. print u"level:", level, "first_parent:", first_parent
  1020. # 如果 others 字段不为空;
  1021. if path_params[level]["others"].__len__():
  1022. # 如果不是跑马灯处理则按照输入密码处理
  1023. if self.dealOthers(level, path_params[level]) is True:
  1024. # print u"解锁失败!!!"
  1025. printLog(u"执行setOptionValue ERROR!option:%s value:%s ;解锁失败!!!" % (str(option), str(value)))
  1026. return False
  1027. cur_option_enter_key = path_params[level]["option_enter_key"]
  1028. # 移动到子节点;
  1029. if cur_option_enter_key.__len__() == 0:
  1030. enter_key = path_params[level]["enter_key"]
  1031. else:
  1032. enter_key = cur_option_enter_key
  1033. move_key = path_params[level]["move_key"]
  1034. if str(move_key) == str([u'up', u'down']) or str(move_key) == str([u'down', u'up']):
  1035. findDirection = str(move_key[1])
  1036. elif str(move_key) == str([u'left', u'right']) or str(move_key) == str([u'right', u'left']):
  1037. findDirection = str(move_key[1])
  1038. else:
  1039. findDirection = 'grid'
  1040. result = self.move2TargetNode(
  1041. level,
  1042. first_parent,
  1043. path_params[level],
  1044. returnKeyEventCount,
  1045. findDirection=findDirection, Max_Try=Max_Try)
  1046. if result is True:
  1047. # 子节点的进入方式默认为ok;
  1048. if enter_key != u'default':
  1049. self.redRat3.sendKey(enter_key)
  1050. # 如果执行一次enter_key,则退出时按返回键的次数加一
  1051. returnKeyEventCount = returnKeyEventCount + 1
  1052. else:
  1053. break
  1054. # end-for
  1055. # 寻路成功,设置叶节点值;
  1056. if result is True:
  1057. # 如果是信源选择 自动选择不需要执行 enter_key
  1058. if self.ocr.cmpOcrStr(option, 'source'):
  1059. return True
  1060. time.sleep(leafNodeValueWaitTime)
  1061. print u"执行设置叶节点:", value_params
  1062. result = self.setLeafNodeValue(
  1063. level,
  1064. first_parent,
  1065. value_params["option"],
  1066. value_params["value"],
  1067. value_params["value_for_ocr"],
  1068. value,
  1069. value_params["move_key"],
  1070. value_params["enter_key"],
  1071. Max_Try=Max_Try)
  1072. # else:
  1073. if returnKeyEventTimes == -1:
  1074. print u"执行退出,执行退出按键次数returnKeyEventCount:", returnKeyEventCount
  1075. # 无论成功失败,要返回到初始界面
  1076. self.redRat3.sendKey("return", returnKeyEventCount, 0.2)
  1077. time.sleep(1)
  1078. # 检测执行回退键是否成功,吐过仍有聚焦效果则继续执行return键
  1079. reCount = 0
  1080. while True:
  1081. if reCount >= returnKeyEventCount:
  1082. printLog(u"执行了returnKeyEventCount:%s次,仍无法退出到初始界面" % str(returnKeyEventCount))
  1083. break
  1084. # isFind, text = self.getCurrentFocusText("First", first_parent)
  1085. # if isFind:
  1086. if self.isFirstOptionShow("First", first_parent, first_option):
  1087. print u"还没有退到初始界面"
  1088. reCount = reCount + 1
  1089. # 如果仍然可以检测到聚焦效果,则继续执行return
  1090. self.redRat3.sendKey("return")
  1091. else:
  1092. printLog(u"回退到初始界面成功!")
  1093. break
  1094. else:
  1095. print u"执行退出,执行退出按键次数returnKeyEventTimes:", returnKeyEventTimes
  1096. # 无论成功失败,要返回到初始界面
  1097. self.redRat3.sendKey("return", returnKeyEventTimes, 0.2)
  1098. if result:
  1099. printLog(u"设置option:%s 选中value:%s的值成功!" % (str(option), str(value)))
  1100. else:
  1101. printLog(u"重新设置option:%s 选中value:%s的值失败!" % (str(option), str(value)))
  1102. # 不再执行重试动作
  1103. # else:
  1104. # if reTryTime < 1:
  1105. # reTryTime = reTryTime + 1
  1106. # result = self.setOptionValue(option, value, reTryTime=reTryTime)
  1107. # if result:
  1108. # printLog(u"重新设置option:%s 选中value:%s的值成功!" % (str(option), str(value)))
  1109. # return True
  1110. # else:
  1111. # printLog(u"重新设置option:%s 选中value:%s的值失败!" % (str(option), str(value)))
  1112. # return False
  1113. # else:
  1114. # printLog(u"设置option:%s 选中value:%s的值尝试2次仍失败!" % (str(option), str(value)))
  1115. # return False
  1116. # 返回结果;
  1117. return result
  1118. # 对外接口:检测操作值是否正确;
  1119. def checkOptionValue(self, option, value, Max_Try=15, leafNodeValueWaitTime=0.0):
  1120. # 切黑场;
  1121. self.sourceInput.setPattern(11)
  1122. printLog(u"开始执行checkOptionValue。option:%s value:%s" % (str(option), str(value)))
  1123. # 寻路结果;
  1124. result = False
  1125. # 获取menu path;
  1126. value_params, path_params = self.uitPathManage.get_menu_paths(option, value)
  1127. printLog(u"获取到达option:%s的路径字典path_params:%s" % (str(option), str(path_params)))
  1128. printLog(u"获取检测value:%s的值字典value_params:%s" % (str(value), str(value_params)))
  1129. checkRunOptionPathResult = self.uitPathManage.checkRunOptionPath(path_params)
  1130. if str(checkRunOptionPathResult) == "NoExit":
  1131. printLog(u"表格中不存在到达Option: %s 的路径,在表格中排查到达该Option路径" % str(option))
  1132. return False
  1133. if str(checkRunOptionPathResult) == "Fail":
  1134. printLog(u"表格中到达Option: %s 的路径出现数据断层找不到First层级,在表格中排查到达该Option路径" % str(option))
  1135. return False
  1136. # returnKeyEventCount = path_params.__len__() + 1
  1137. returnKeyEventCount = 0
  1138. print "returnKeyEventCount:", returnKeyEventCount
  1139. # 逆序路径key;
  1140. revpp = reversed(path_params)
  1141. # 根节点是否已进入;
  1142. entry = False
  1143. root = u''
  1144. first_parent = u''
  1145. first_option = u''
  1146. # 遍历路径(已排序,从first开始);
  1147. # print "revpp:", revpp
  1148. for level in revpp:
  1149. # print "level:", level, path_params[level]
  1150. printLog(u"执行路径level:%s 对应路径字典:%s" % (str(level), str(path_params[level])))
  1151. # 是否进入根结点;
  1152. if entry == False:
  1153. # 标记已进入根;
  1154. entry = True
  1155. first_parent = path_params[level]["parent"]
  1156. first_option = path_params[level]["option"]
  1157. checkFirstOptionTimes = 0
  1158. while True:
  1159. if checkFirstOptionTimes > 2:
  1160. errorPngName = "menutree_error_" + str(option) + '_' + str(value) + self.currentTime() + ".png"
  1161. error_uiPic = os.path.join(getSATTmpDIR(), errorPngName)
  1162. self.ccard.takePicture(error_uiPic)
  1163. printLog(u"执行checkOptionValue ERROR!option:%s value:%s ;尝试3次快捷按键仍然没有唤出聚焦焦点界面!!! 出错截图:%s" % (
  1164. str(option), str(value), str(error_uiPic)))
  1165. return False
  1166. printLog(u"第%s次尝试呼出一级界面" % str(checkFirstOptionTimes))
  1167. # # 进入根节点(根节点名就是遥控键名);
  1168. # self.redRat3.sendKey(path_params[level]["parent"])
  1169. # 判断是否存在others字段,others字段中存在first_key,则优先使用first_key进入
  1170. try:
  1171. others = json.loads(path_params[level]["others"])
  1172. except Exception,e:
  1173. others = {}
  1174. printLog("section others:%s"%others)
  1175. if "first_key" in others.keys():
  1176. first_key = others["first_key"]
  1177. else:
  1178. first_key = path_params[level]["parent"]
  1179. printLog(u"进入根节点,first_key:%s"%first_key)
  1180. # 进入根节点
  1181. self.redRat3.sendKey(first_key)
  1182. waitTime = self.getParentWaitTime(path_params[level]["parent"])
  1183. printLog(u"打开%s界面的等待时间waittime为:%s" % (str(path_params[level]["parent"]), str(waitTime)))
  1184. time.sleep(waitTime)
  1185. # 获取ocr列表;
  1186. self.get_ocr_list(level, option)
  1187. if self.isFirstOptionShow(level, first_parent, first_option):
  1188. printLog(u"呼出一级菜单界面")
  1189. break
  1190. else:
  1191. time.sleep(5)
  1192. self.redRat3.sendKey("return", 1)
  1193. checkFirstOptionTimes = checkFirstOptionTimes + 1
  1194. # 如果一级界面弹出成功,则退出时候返回按键次数加1
  1195. returnKeyEventCount = returnKeyEventCount + 1
  1196. # 如果 others 字段不为空;
  1197. if path_params[level]["others"].__len__():
  1198. # 如果不是跑马灯处理则按照输入密码处理
  1199. if self.dealOthers(level, path_params[level]) is True:
  1200. # print u"解锁失败!!!"
  1201. printLog(u"执行checkOptionValue ERROR!option:%s value:%s ;解锁失败!!!" % (str(option), str(value)))
  1202. return False
  1203. # 移动到子节点;
  1204. cur_option_enter_key = path_params[level]["option_enter_key"]
  1205. # 移动到子节点;
  1206. if cur_option_enter_key.__len__() == 0:
  1207. enter_key = path_params[level]["enter_key"]
  1208. else:
  1209. enter_key = cur_option_enter_key
  1210. move_key = path_params[level]["move_key"]
  1211. if str(move_key) == str([u'up', u'down']) or str(move_key) == str([u'down', u'up']):
  1212. findDirection = str(move_key[1])
  1213. elif str(move_key) == str([u'left', u'right']) or str(move_key) == str([u'right', u'left']):
  1214. findDirection = str(move_key[1])
  1215. else:
  1216. findDirection = 'grid'
  1217. result = self.move2TargetNode(
  1218. level,
  1219. first_parent,
  1220. path_params[level],
  1221. returnKeyEventCount,
  1222. findDirection=findDirection, Max_Try=Max_Try)
  1223. if result is True:
  1224. # 子节点的进入方式默认为ok;
  1225. # self.redRat3.sendKey('ok')
  1226. # 子节点的进入方式默认为ok;
  1227. if enter_key != u'default':
  1228. self.redRat3.sendKey(enter_key)
  1229. # 如果执行一次enter_key,则退出时按返回键的次数加一
  1230. returnKeyEventCount = returnKeyEventCount + 1
  1231. else:
  1232. break
  1233. # end-for
  1234. # 寻路成功,设置叶节点值;
  1235. if result is True:
  1236. # 如果是信源选择 自动选择不需要执行 enter_key
  1237. if self.ocr.cmpOcrStr(option, 'source') or self.ocr.cmpOcrStr(option, 'ok'):
  1238. return True
  1239. time.sleep(leafNodeValueWaitTime)
  1240. result = self.checkLeafNodeValue(level, root, value_params["option"],
  1241. value_params["value"],
  1242. value_params["value_for_ocr"],
  1243. value)
  1244. print u"执行退出,执行退出按键次数returnKeyEventCount:", returnKeyEventCount
  1245. # 无论成功失败,要返回到初始界面
  1246. self.redRat3.sendKey("return", returnKeyEventCount, 0.2)
  1247. time.sleep(1)
  1248. # 检测执行回退键是否成功,吐过仍有聚焦效果则继续执行return键
  1249. reCount = 0
  1250. while True:
  1251. if reCount >= returnKeyEventCount:
  1252. printLog(u"执行了returnKeyEventCount:%s次,仍无法退出到初始界面" % str(returnKeyEventCount))
  1253. break
  1254. if self.isFirstOptionShow("First", first_parent, first_option):
  1255. reCount = reCount + 1
  1256. # 如果仍然可以检测到聚焦效果,则继续执行return
  1257. self.redRat3.sendKey("return")
  1258. else:
  1259. printLog(u"回退到初始界面成功!")
  1260. break
  1261. if result:
  1262. printLog(u"检测option:%s 选中value:%s的值成功!" % (str(option), str(value)))
  1263. else:
  1264. printLog(u"检测option:%s 选中value:%s的值失败!" % (str(option), str(value)))
  1265. # 返回结果;
  1266. return result
  1267. def checkLeafNodeValue(self, level, parent, option, value_excel, value_for_ocr, value):
  1268. # 获取等待时间
  1269. waitTime = self.getOptionWaitTime(option)
  1270. printLog(u"checkLeafNodeValue:获取到进入叶节点%s,等待时间为%s"%(option, waitTime))
  1271. time.sleep(waitTime)
  1272. value_for_ocr_low = str(value_for_ocr[0]).lower()
  1273. # 判断设置值的类型 是rang类型还是str类型
  1274. if "range(" in value_for_ocr_low:
  1275. isRangeType = True
  1276. str_num = value_for_ocr_low.replace("range", "")
  1277. list_num = eval(str_num)
  1278. min_num = list_num[0]
  1279. max_num = list_num[1]
  1280. try:
  1281. value_num = int(value)
  1282. except Exception:
  1283. printLog(u"传入的值value:%S和option:%s对应的类型不匹配 !" % (str(value), str(option)))
  1284. return False
  1285. else:
  1286. isRangeType = False
  1287. if isRangeType:
  1288. # 设置数值范围类型的处理
  1289. isFind, text, text_num = self.getCurrentFocusOcr_Int(level, parent, option=option, isForValue=True)
  1290. if not isFind:
  1291. errorPngName = "menutree_error_" + str(option) + str(value_excel) + self.currentTime() + ".png"
  1292. error_uiPic = os.path.join(getSATTmpDIR(), errorPngName)
  1293. self.ccard.takePicture(error_uiPic)
  1294. printLog(u"检测叶子节点值时,当前界面无法找到焦点区域!!!出错界面截图%s" % str(error_uiPic))
  1295. return False
  1296. else:
  1297. pass
  1298. try:
  1299. list_text_num = getDigitFromString(text)
  1300. if list_text_num.__len__() < 1:
  1301. errorPngName = "menutree_error_" + str(option) + '_' + str(
  1302. value_excel) + self.currentTime() + ".png"
  1303. error_uiPic = os.path.join(getSATTmpDIR(), errorPngName)
  1304. self.ccard.takePicture(error_uiPic)
  1305. printLog(u"检测叶子节点值时,当前option:%s 识别出来的值text:%s 不包含int类型值,截图为:%s" % (
  1306. str(option), str(text), str(error_uiPic)))
  1307. return False
  1308. text_int_str = list_text_num[list_text_num.__len__() - 1]
  1309. # print 'text_int_str:', text_int_str
  1310. text_num = int(text_int_str)
  1311. printLog(u"检测到的值text_num:%s" % str(text_num))
  1312. except Exception:
  1313. errorPngName = "menutree_error_" + str(option) + '_' + str(
  1314. value_excel) + self.currentTime() + ".png"
  1315. error_uiPic = os.path.join(getSATTmpDIR(), errorPngName)
  1316. self.ccard.takePicture(error_uiPic)
  1317. printLog(u"检测叶子节点值时,当前option:%s 识别出来的值text:%s 不能转换成value_for_ocr:%s范围内的int类型,截图为:%s" % (
  1318. str(option), str(text_int_str), str(value_for_ocr), str(error_uiPic)))
  1319. return False
  1320. if text_num < min_num or text_num > max_num:
  1321. errorPngName = "menutree_error_" + str(option) + '_' + str(
  1322. value_excel) + self.currentTime() + ".png"
  1323. error_uiPic = os.path.join(getSATTmpDIR(), errorPngName)
  1324. self.ccard.takePicture(error_uiPic)
  1325. printLog(u"检测叶子节点值时,当前option:%s 识别出来的值text:%s 不在value_for_ocr:%s范围内,截图为:%s" % (
  1326. str(option), str(text), str(value_for_ocr), str(error_uiPic)))
  1327. return False
  1328. # if abs(text_num) == abs(value_num):
  1329. if text_num == value_num:
  1330. printLog(u"检测叶子节点值时,聚焦到目标option:%s,检测value:%s选项成功!" % (str(option), str(value_excel)))
  1331. return True
  1332. else:
  1333. return False
  1334. else:
  1335. # 设置选项类型的处理
  1336. isFind, text = self.getCurrentFocusTextEx(level, parent, option, value_excel, value_for_ocr,
  1337. isForValue=True)
  1338. if not isFind:
  1339. errorPngName = "menutree_error_" + str(option) + '_' + str(value_excel) + self.currentTime() + ".png"
  1340. error_uiPic = os.path.join(getSATTmpDIR(), errorPngName)
  1341. self.ccard.takePicture(error_uiPic)
  1342. printLog(u"检测叶子节点值时,当前界面无法找到焦点区域!!!出错界面截图:%s" % str(error_uiPic))
  1343. return False
  1344. # elif (self.ocr.cmpOcrStr(text, value_for_ocr)):
  1345. # 由比较目标文本和识别文本 是否相等 改为 识别文本是否包含目标文本
  1346. else:
  1347. for value_for_ocr_text in value_for_ocr:
  1348. value_for_ocr_text_low = str(value_for_ocr_text).lower()
  1349. if value_for_ocr_text_low in text:
  1350. printLog(u"检测叶子节点值时,聚焦到目标option:%s,检测value:%s选项成功!" % (str(option), str(value_excel)))
  1351. return True
  1352. errorPngName = "menutree_error_" + str(option) + '_' + str(value_excel) + self.currentTime() + ".png"
  1353. error_uiPic = os.path.join(getSATTmpDIR(), errorPngName)
  1354. self.ccard.takePicture(error_uiPic)
  1355. printLog(u"检测叶子节点值时,聚焦到目标option:%s,检测value:%s选项失败!出错界面截图:%s" % (
  1356. str(option), str(value_excel), str(error_uiPic)))
  1357. return False
  1358. # 对外接口:信源设置接口;本方法(先识别再切换)NT72项目由于界面消失太快不适用,下面封的接口逻辑(先切换再识别)
  1359. # def setSourceValue(self, option, value, sourceWaitTime=1.0, Max_Try=10):
  1360. # printLog(u"开始执行setSourceValue。option:%s value:%s" % (str(option), str(value)))
  1361. # # self.get_ocr_list('First', 'source')
  1362. # # 获取menu path;
  1363. # value_params, path_params = self.xlsparser.get_menu_paths(option, value)
  1364. # # print "value_params:", value_params
  1365. # printLog(u"获取设置信源value:%s的值字典value_params:%s" % (str(value), str(value_params)))
  1366. # value_for_ocr = value_params['value_for_ocr']
  1367. #
  1368. # old_text = "init_old_text"
  1369. #
  1370. # enter_key = value_params["enter_key"]
  1371. # move_key = value_params["move_key"]
  1372. # if str(move_key) == str([u'up', u'down']):
  1373. # findDirection = "down"
  1374. # findReverseDirection = "up"
  1375. # else:
  1376. # findDirection = "right"
  1377. # findReverseDirection = "left"
  1378. # # 正向寻找的次数计数和最大次数
  1379. # count = 0
  1380. # Max_Try = Max_Try
  1381. # # 反向寻找的次数计数和最大次数
  1382. # Reversecount = 0
  1383. # Reverse_Max_Try = Max_Try * 2
  1384. # sourceWaitTime = self.tconfig.get_value("waitTime", "sourceWaitTime")
  1385. # if not sourceWaitTime:
  1386. # sourceWaitTime = 1.0
  1387. # while True:
  1388. # if count >= Max_Try and Reversecount >= Reverse_Max_Try:
  1389. # return False
  1390. # time.sleep(2)
  1391. # self.redRat3.sendKey('source')
  1392. # time.sleep(sourceWaitTime)
  1393. # isFind, text = self.getCurrentFocusTextEx('First', 'source', 'source', option, value_for_ocr, True)
  1394. # if isFind == -1:
  1395. # # 6586自研机芯USB进入之后无法唤出信源 按return再一次按source呼出界面
  1396. # self.redRat3.sendKey("return")
  1397. # self.redRat3.sendKey('source')
  1398. # time.sleep(0.2)
  1399. # isFind, text = self.getCurrentFocusTextEx('First', 'source', 'source', option, value_for_ocr, True)
  1400. # if isFind == -1:
  1401. # printLog(u"当前界面找不到焦点!即source没有调出信源界面")
  1402. # return False
  1403. #
  1404. # if isFind == 1:
  1405. # printLog(u"聚焦到目标option:%s,设置信源value:%s选项成功!" % (str(option), str(value)))
  1406. # # 聚焦成功发送enter_key
  1407. # self.redRat3.sendKey('ok')
  1408. # return True
  1409. # # 判断两次识别
  1410. # print "text:", text, "old_text:", old_text, self.ocr.cmpOcrStr(text, old_text)
  1411. #
  1412. # # 判断信源界面有没有消失 如果消失再次按出信源界面
  1413. # isFind_source, text = self.getCurrentFocusTextEx('First', 'source', 'source', option, value_for_ocr, True)
  1414. # if isFind_source == -1:
  1415. # self.redRat3.sendKey('source')
  1416. # time.sleep(sourceWaitTime)
  1417. #
  1418. # # 判断两次识别的text是否相等来判断是否到达边界
  1419. # if self.ocr.cmpOcrStr(text, old_text):
  1420. # # 如果已经到达边界则不再正方向寻找焦点
  1421. # count = Max_Try
  1422. # old_text = "init_old_text"
  1423. # else:
  1424. # old_text = text
  1425. #
  1426. # if count < Max_Try:
  1427. # count = count + 1
  1428. # self.redRat3.sendKey(findDirection)
  1429. # self.redRat3.sendKey('ok')
  1430. # else:
  1431. # Reversecount = Reversecount + 1
  1432. # self.redRat3.sendKey(findReverseDirection)
  1433. # self.redRat3.sendKey('ok')
  1434. #
  1435. # errorPngName = "menutree_error_" + str(option) + '_' + str(value) + self.currentTime() + ".png"
  1436. # error_uiPic = os.path.join(getSATTmpDIR(), errorPngName)
  1437. # self.ccard.takePicture(error_uiPic)
  1438. # printLog(u"设置信源值时,正向遍历%s次,和反向遍历%s次都没有聚焦到option:%s的value:%s选项中,截图为%s" % (
  1439. # str(Max_Try), str(Reverse_Max_Try), str(option), str(value), str(error_uiPic)))
  1440. # return False
  1441. # 对外接口:信源设置接口; 先切换再识别
  1442. '''
  1443. 不允许切换信源,在MenuTree.ini文件中配置:source={"offset":20,"minPeri":0,"maxPeri":0,"minArea":0,"maxArea":0,"enable":0}。
  1444. enable没有,默认值enable=1;enable=0,表示不允许切换信源,仅判断是否为目标信源。
  1445. '''
  1446. def setSourceValue(self, option, value, sourceWaitTime=1.0, Max_Try=10):
  1447. # 切黑场;
  1448. self.sourceInput.setPattern(11)
  1449. return self.tSource.setSourceValue(option, value, sourceWaitTime, Max_Try)
  1450. def inputUnlock(self, std_str, password=''):
  1451. # 如果锁住,按ok会弹出输入密码框;
  1452. self.redRat3.sendKey("ok")
  1453. # 获取密码;
  1454. if password.__len__() == 0:
  1455. password = self.tconfig.get_value("Password", "super")
  1456. # 发送按键;
  1457. for key in list(password):
  1458. self.redRat3.sendKey(key, 1, 0.2)
  1459. time.sleep(1)
  1460. # 发送ok键;
  1461. self.redRat3.sendKey('ok')
  1462. # 判断是否成功输入密码;
  1463. current_uiPic = self.getCurrentUIPath()
  1464. self.get_ocr_list("", "")
  1465. # 遍历ocr类型;
  1466. found = False
  1467. for item in self.ocrDict:
  1468. # 识别ocr;
  1469. ocr_str = self.ocr.getStrWithImgProcess(current_uiPic, {}, item["lan"], item["type"], reconTimes=1)
  1470. ocr_str = unicode(ocr_str).lower()
  1471. # print("lan=%s,type=%d,ocr=%s" % (item["lan"], item["type"], ocr_str))
  1472. printLog("lan=%s,type=%d,ocr=%s" % (item["lan"], item["type"], ocr_str))
  1473. if ocr_str in std_str or std_str == ocr_str:
  1474. found = True
  1475. break
  1476. return not found
  1477. def openOption(self, option, Max_Try=15):
  1478. # 切黑场;
  1479. self.sourceInput.setPattern(11)
  1480. # 获取menu path;
  1481. print "openOption start >>>"
  1482. path_params = self.uitPathManage.get_option_paths(option)
  1483. # print 'openOption=path_params:', path_params
  1484. printLog('openOption=path_params:%s' % str(path_params))
  1485. checkRunOptionPathResult = self.uitPathManage.checkRunOptionPath(path_params)
  1486. if str(checkRunOptionPathResult) == "NoExit":
  1487. printLog(u"表格中不存在到达Option: %s 的路径,在表格中排查到达该Option路径" % str(option))
  1488. return False
  1489. if str(checkRunOptionPathResult) == "Fail":
  1490. printLog(u"表格中到达Option: %s 的路径出现数据断层找不到First层级,在表格中排查到达该Option路径" % str(option))
  1491. return False
  1492. # returnKeyEventCount = path_params.__len__() + 1
  1493. returnKeyEventCount = 0
  1494. print "returnKeyEventCount:", returnKeyEventCount
  1495. printLog("openOption=returnKeyEventCount:%s" % str(returnKeyEventCount))
  1496. # 逆序路径key;
  1497. revpp = reversed(path_params)
  1498. # 根节点是否已进入;
  1499. entry = False
  1500. first_parent = u''
  1501. first_option = u''
  1502. # 遍历路径(已排序,从first开始);
  1503. # print "revpp:", revpp
  1504. printLog("openOption=revpp:%s" % str(revpp))
  1505. for level in revpp:
  1506. # print "openOption=level:", path_params[level]
  1507. printLog("openOption=level:", path_params[level])
  1508. # 是否进入根结点;
  1509. if entry == False:
  1510. # 标记已进入根;
  1511. entry = True
  1512. first_parent = path_params[level]["parent"]
  1513. first_option = path_params[level]["option"]
  1514. checkFirstOptionTimes = 0
  1515. while True:
  1516. if checkFirstOptionTimes > 2:
  1517. printLog(u"openOption=尝试3次快捷按键没有唤出聚焦焦点界面!!!")
  1518. return False
  1519. printLog(u"第%s次尝试呼出一级界面" % str(checkFirstOptionTimes))
  1520. # # 进入根节点(根节点名就是遥控键名);
  1521. # self.redRat3.sendKey(path_params[level]["parent"])
  1522. # 判断是否存在others字段,others字段中存在first_key,则优先使用first_key进入
  1523. try:
  1524. others = json.loads(path_params[level]["others"])
  1525. except Exception,e:
  1526. others = {}
  1527. printLog("section others:%s"%others)
  1528. if "first_key" in others.keys():
  1529. first_key = others["first_key"]
  1530. else:
  1531. first_key = path_params[level]["parent"]
  1532. printLog(u"进入根节点,first_key:%s"%first_key)
  1533. # 进入根节点
  1534. self.redRat3.sendKey(first_key)
  1535. waitTime = self.getParentWaitTime(path_params[level]["parent"])
  1536. printLog(u"打开%s界面的等待时间waittime为:%s" % (str(path_params[level]["parent"]), str(waitTime)))
  1537. time.sleep(waitTime)
  1538. # 获取ocr列表;
  1539. self.get_ocr_list(level, option)
  1540. if self.isFirstOptionShow(level, first_parent, first_option):
  1541. printLog(u"呼出一级菜单界面")
  1542. break
  1543. else:
  1544. time.sleep(5)
  1545. self.redRat3.sendKey("return", 2)
  1546. checkFirstOptionTimes = checkFirstOptionTimes + 1
  1547. # 如果一级界面弹出成功,则退出时候返回按键次数加1
  1548. returnKeyEventCount = returnKeyEventCount + 1
  1549. # 如果 others 字段不为空;
  1550. if path_params[level]["others"].__len__():
  1551. # 如果不是跑马灯处理则按照输入密码处理
  1552. if self.dealOthers(level, path_params[level]) is True:
  1553. # print u"解锁失败!!!"
  1554. printLog(u"openOption=解锁失败!!!")
  1555. return False
  1556. # 移动到子节点;
  1557. cur_option_enter_key = path_params[level]["option_enter_key"]
  1558. # 移动到子节点;
  1559. if cur_option_enter_key.__len__() == 0:
  1560. enter_key = path_params[level]["enter_key"]
  1561. else:
  1562. enter_key = cur_option_enter_key
  1563. move_key = path_params[level]["move_key"]
  1564. if str(move_key) == str([u'up', u'down']) or str(move_key) == str([u'down', u'up']):
  1565. findDirection = str(move_key[1])
  1566. elif str(move_key) == str([u'left', u'right']) or str(move_key) == str([u'right', u'left']):
  1567. findDirection = str(move_key[1])
  1568. else:
  1569. findDirection = 'grid'
  1570. result = self.move2TargetNode(
  1571. level,
  1572. first_parent,
  1573. path_params[level],
  1574. returnKeyEventCount,
  1575. findDirection=findDirection, Max_Try=Max_Try)
  1576. if result is True:
  1577. # 子节点的进入方式默认为ok;
  1578. self.redRat3.sendKey(enter_key)
  1579. # 如果执行一次enter_key,则退出时按返回键的次数加一
  1580. if enter_key != u'default':
  1581. returnKeyEventCount = returnKeyEventCount + 1
  1582. else:
  1583. print "openOption end<<<<"
  1584. return False
  1585. # end-for
  1586. print "openOption end <<<<"
  1587. return True
  1588. # 对外接口:检测频道列表;
  1589. def checkChannelList(self, channelList, Max_Try=15):
  1590. failChannelList = []
  1591. checkResult = True
  1592. if channelList == []:
  1593. printLog(u"传入的待检测的频道列表为空!")
  1594. return False, failChannelList
  1595. for channel in channelList:
  1596. isSearched = self.checkOptionValue("ok", channel, Max_Try=Max_Try)
  1597. if not isSearched:
  1598. printLog(u"频道:%s查找失败!" % str(channel))
  1599. failChannelList.append(channel)
  1600. checkResult = False
  1601. # 部分机芯项目(如6586外协松下)按return键无法退出频道,故改为exit键
  1602. # self.redRat3.sendKey("return")
  1603. self.redRat3.sendKey("exit")
  1604. else:
  1605. printLog(u"频道:%s查找成功!" % str(channel))
  1606. self.redRat3.sendKey("exit")
  1607. printLog(u"频道列表检测结果checkResult:%s,检测失败频道列表failChannelLis:%s" % (str(checkResult), str(failChannelList)))
  1608. return checkResult, failChannelList
  1609. # 对外唯一接口:设置操作值;
  1610. def focusOptionValue(self, option, value, Max_Try=15, leafNodeValueWaitTime=0.0):
  1611. # 切黑场;
  1612. self.sourceInput.setPattern(11)
  1613. printLog(u"focusOptionValue。option:%s value:%s" % (str(option), str(value)))
  1614. # 寻路结果;
  1615. result = False
  1616. # 获取menu path;
  1617. value_params, path_params = self.uitPathManage.get_menu_paths(option, value)
  1618. printLog(u"获取到达option:%s的路径字典path_params:%s" % (str(option), str(path_params)))
  1619. printLog(u"获取聚焦value:%s的值字典value_params:%s" % (str(value), str(value_params)))
  1620. checkRunOptionPathResult = self.uitPathManage.checkRunOptionPath(path_params)
  1621. if str(checkRunOptionPathResult) == "NoExit":
  1622. printLog(u"表格中不存在到达Option: %s 的路径,在表格中排查到达该Option路径" % str(option))
  1623. return False
  1624. if str(checkRunOptionPathResult) == "Fail":
  1625. printLog(u"表格中到达Option: %s 的路径出现数据断层找不到First层级,在表格中排查到达该Option路径" % str(option))
  1626. return False
  1627. # returnKeyEventCount = path_params.__len__() + 1
  1628. returnKeyEventCount = 0
  1629. print "returnKeyEventCount:", returnKeyEventCount
  1630. # 逆序路径key;
  1631. revpp = reversed(path_params)
  1632. # 根节点是否已进入;
  1633. entry = False
  1634. root = u''
  1635. first_parent = u''
  1636. first_option = u''
  1637. # 遍历路径(已排序,从first开始);
  1638. # print "revpp:", revpp
  1639. for level in revpp:
  1640. # print "level:", level, path_params[level]
  1641. printLog(u"执行路径level:%s 对应路径字典:%s" % (str(level), str(path_params[level])))
  1642. # 是否进入根结点;
  1643. if entry == False:
  1644. # 标记已进入根;
  1645. entry = True
  1646. first_parent = path_params[level]["parent"]
  1647. first_option = path_params[level]["option"]
  1648. checkFirstOptionTimes = 0
  1649. while True:
  1650. if checkFirstOptionTimes > 2:
  1651. errorPngName = "menutree_error_" + str(option) + '_' + str(value) + self.currentTime() + ".png"
  1652. error_uiPic = os.path.join(getSATTmpDIR(), errorPngName)
  1653. self.ccard.takePicture(error_uiPic)
  1654. printLog(u"执行focusOptionValue ERROR!option:%s value:%s ;尝试3次快捷按键仍然没有唤出聚焦焦点界面!!! 出错截图:%s" % (
  1655. str(option), str(value), str(error_uiPic)))
  1656. return False
  1657. printLog(u"第%s次尝试呼出一级界面" % str(checkFirstOptionTimes))
  1658. # # 进入根节点(根节点名就是遥控键名);
  1659. # self.redRat3.sendKey(path_params[level]["parent"])
  1660. # 判断是否存在others字段,others字段中存在first_key,则优先使用first_key进入
  1661. try:
  1662. others = json.loads(path_params[level]["others"])
  1663. except Exception,e:
  1664. others = {}
  1665. printLog("section others:%s"%others)
  1666. if "first_key" in others.keys():
  1667. first_key = others["first_key"]
  1668. else:
  1669. first_key = path_params[level]["parent"]
  1670. printLog(u"进入根节点,first_key:%s"%first_key)
  1671. # 进入根节点
  1672. self.redRat3.sendKey(first_key)
  1673. waitTime = self.getParentWaitTime(path_params[level]["parent"])
  1674. printLog(u"打开%s界面的等待时间waittime为:%s" % (str(path_params[level]["parent"]), str(waitTime)))
  1675. time.sleep(waitTime)
  1676. # 获取ocr列表;
  1677. self.get_ocr_list(level, option)
  1678. if self.isFirstOptionShow(level, first_parent, first_option):
  1679. printLog(u"呼出一级菜单界面")
  1680. break
  1681. else:
  1682. time.sleep(5)
  1683. self.redRat3.sendKey("return", 2)
  1684. checkFirstOptionTimes = checkFirstOptionTimes + 1
  1685. # 如果一级界面弹出成功,则退出时候返回按键次数加1
  1686. returnKeyEventCount = returnKeyEventCount + 1
  1687. print "level:", level, "root:", root
  1688. # 如果 others 字段不为空;
  1689. if path_params[level]["others"].__len__():
  1690. # 如果不是跑马灯处理则按照输入密码处理
  1691. if self.dealOthers(level, path_params[level]) is True:
  1692. # print u"解锁失败!!!"
  1693. printLog(u"执行setOptionValue ERROR!option:%s value:%s ;解锁失败!!!" % (str(option), str(value)))
  1694. return False
  1695. # 移动到子节点;
  1696. cur_option_enter_key = path_params[level]["option_enter_key"]
  1697. # 移动到子节点;
  1698. if cur_option_enter_key.__len__() == 0:
  1699. enter_key = path_params[level]["enter_key"]
  1700. else:
  1701. enter_key = cur_option_enter_key
  1702. move_key = path_params[level]["move_key"]
  1703. if str(move_key) == str([u'up', u'down']) or str(move_key) == str([u'down', u'up']):
  1704. findDirection = str(move_key[1])
  1705. elif str(move_key) == str([u'left', u'right']) or str(move_key) == str([u'right', u'left']):
  1706. findDirection = str(move_key[1])
  1707. else:
  1708. findDirection = 'grid'
  1709. result = self.move2TargetNode(
  1710. level,
  1711. first_parent,
  1712. path_params[level],
  1713. returnKeyEventCount,
  1714. findDirection=findDirection, Max_Try=Max_Try)
  1715. if result is True:
  1716. # 子节点的进入方式默认为ok;
  1717. # self.redRat3.sendKey('ok')
  1718. # 如果只一层,不进行enter_key执行
  1719. if path_params.__len__() != 1:
  1720. self.redRat3.sendKey(enter_key)
  1721. # 如果执行一次enter_key,则退出时按返回键的次数加一
  1722. if enter_key != u'default':
  1723. returnKeyEventCount = returnKeyEventCount + 1
  1724. else:
  1725. break
  1726. # end-for
  1727. # 如果只一层不进行focusLeafNodeValue设置
  1728. if path_params.__len__() != 1:
  1729. # 寻路成功,设置叶节点值;
  1730. if result is True:
  1731. # 如果是信源选择 自动选择不需要执行 enter_key
  1732. if self.ocr.cmpOcrStr(option, 'source'):
  1733. return True
  1734. time.sleep(leafNodeValueWaitTime)
  1735. print u"执行设置叶节点:", value_params
  1736. result = self.focusLeafNodeValue(
  1737. level,
  1738. root,
  1739. value_params["option"],
  1740. value_params["value"],
  1741. value_params["value_for_ocr"],
  1742. value,
  1743. value_params["move_key"],
  1744. value_params["enter_key"],
  1745. Max_Try=Max_Try)
  1746. # 无论成功失败,要返回到初始界面
  1747. if result:
  1748. # 如果执行成功则不返回到初始界面
  1749. printLog(u"设置option:%s 选中value:%s的值成功!" % (str(option), str(value)))
  1750. else:
  1751. printLog(u"设置option:%s 选中value:%s的值失败!" % (str(option), str(value)))
  1752. print u"执行退出,执行退出按键次数returnKeyEventCount:", returnKeyEventCount
  1753. # 执行聚焦失败时候,返回到初始界面
  1754. self.redRat3.sendKey("return", returnKeyEventCount, 0.2)
  1755. time.sleep(1)
  1756. # 检测执行回退键是否成功,吐过仍有聚焦效果则继续执行return键
  1757. reCount = 0
  1758. while True:
  1759. if reCount >= returnKeyEventCount:
  1760. printLog(u"执行了returnKeyEventCount:%s次,仍无法退出到初始界面" % str(returnKeyEventCount))
  1761. break
  1762. if self.isFirstOptionShow("First", first_parent, first_option):
  1763. reCount = reCount + 1
  1764. # 如果仍然可以检测到聚焦效果,则继续执行return
  1765. self.redRat3.sendKey("return")
  1766. else:
  1767. printLog(u"回退到初始界面成功!")
  1768. break
  1769. # 返回结果;
  1770. return result
  1771. # 设置叶子节点值;
  1772. def focusLeafNodeValue(self, level, parent, option, value_excel, value_for_ocr, value, move_key, enter_key,
  1773. Max_Try=15):
  1774. # 按照传入的方向寻找Max_Try次,如果仍未聚焦到option_for_ocr所在的区域,则按照传入方向的反方向 反向寻找 2*Max_Try 次
  1775. # 正向寻找的次数计数和最大次数
  1776. count = 0
  1777. Max_Try = Max_Try
  1778. # 反向寻找的次数计数和最大次数
  1779. Reversecount = 0
  1780. Reverse_Max_Try = Max_Try * 2
  1781. # 记录上一个焦点识别的文字内容 用于判断是否到达列表的边界 如果到达边界则反向寻找
  1782. old_text = "init_old_text"
  1783. # 正向寻找的遥控器按键值
  1784. findDirection = move_key[1] # 向右或者向下
  1785. # 反向寻找的遥控器按键值
  1786. findReverseDirection = move_key[0] # 向左或者向上
  1787. # 获取等待时间
  1788. waitTime = self.getLeafWaitTime(option)
  1789. printLog(u"focusLeafNodeValue:获取到进入叶节点%s,等待时间为%s"%(option, waitTime))
  1790. time.sleep(waitTime)
  1791. value_for_ocr_low = str(value_for_ocr[0]).lower()
  1792. # 判断设置值的类型 是rang类型还是str类型
  1793. if "range(" in value_for_ocr_low:
  1794. isRangeType = True
  1795. str_num = value_for_ocr_low.replace("range", "")
  1796. list_num = eval(str_num)
  1797. min_num = list_num[0]
  1798. max_num = list_num[1]
  1799. try:
  1800. value_num = int(value)
  1801. except Exception:
  1802. printLog(u"传入的值value:%s和option:%s对应的类型不匹配 !" % (str(value), str(option)))
  1803. return False
  1804. else:
  1805. isRangeType = False
  1806. if isRangeType:
  1807. # 如果是数值类型,则直接返回聚焦成功
  1808. return True
  1809. else:
  1810. # 设置选项类型的处理
  1811. while (True):
  1812. print "count:", count
  1813. if count >= Max_Try and Reversecount >= Reverse_Max_Try:
  1814. break
  1815. isFind, text = self.getCurrentFocusTextEx(level, parent, option, value_excel, value_for_ocr,
  1816. isForValue=True)
  1817. if isFind == -1:
  1818. errorPngName = "menutree_error_" + str(option) + '_' + str(
  1819. value_excel) + self.currentTime() + ".png"
  1820. error_uiPic = os.path.join(getSATTmpDIR(), errorPngName)
  1821. self.ccard.takePicture(error_uiPic)
  1822. printLog(u"聚焦叶子节点值时,当前界面无法找到焦点区域!!!出错界面截图%s" % str(error_uiPic))
  1823. return False
  1824. # elif (self.ocr.cmpOcrStr(text, value_for_ocr)):
  1825. # 由比较目标文本和识别文本 是否相等 改为 识别文本是否包含目标文本
  1826. else:
  1827. if isFind == 1:
  1828. printLog(u"聚焦到目标option:%s,设置value:%s选项成功!" % (str(option), str(value_excel)))
  1829. # 聚焦到某个焦点成功,由于是聚焦接口调用,不用send enter_key进入到焦点
  1830. # if enter_key != 'default':
  1831. # self.redRat3.sendKey(enter_key)
  1832. return True
  1833. # 判断两次识别
  1834. # 判断两次识别的text是否相等来判断是否到达边界
  1835. if self.ocr.cmpOcrStr(text, old_text):
  1836. # 如果已经到达边界则不再正方向寻找焦点
  1837. count = Max_Try
  1838. old_text = "init_old_text"
  1839. else:
  1840. old_text = text
  1841. if count < Max_Try:
  1842. count = count + 1
  1843. self.redRat3.sendKey(findDirection)
  1844. else:
  1845. Reversecount = Reversecount + 1
  1846. self.redRat3.sendKey(findReverseDirection)
  1847. errorPngName = "menutree_error_" + str(option) + '_' + str(value_excel) + self.currentTime() + ".png"
  1848. error_uiPic = os.path.join(getSATTmpDIR(), errorPngName)
  1849. self.ccard.takePicture(error_uiPic)
  1850. printLog(u"聚焦叶子节点值时,正向遍历%s次,和反向遍历%s次都没有聚焦到option:%s的value:%s选项中,截图为%s" % (
  1851. str(Max_Try), str(Reverse_Max_Try), str(option), str(value_excel), str(error_uiPic)))
  1852. return False
  1853. return True
  1854. def getOptionValue(self, option, is_value_sheet=True):
  1855. # 切黑场;
  1856. self.sourceInput.setPattern(11)
  1857. # 获取路径参数;
  1858. result, option_data = self.uitRunner.uitData.UITree.get_option(option)
  1859. if result is False:
  1860. print(u"getOptionValue.获取option菜单内容失败")
  1861. return False, ''
  1862. first_parent = option_data['first_parent']
  1863. thresholdDict = self.tconfig.getThresholdDict(first_parent)
  1864. # 根据parent打开特定的option;
  1865. if self.openOption(option) is False:
  1866. self.redRat3.sendKey('return', option_data['layers'] + 1, 0.2)
  1867. print(u"getOptionValue.进入指定option失败")
  1868. return False, ''
  1869. # 获取等待时间
  1870. waitTime = self.getOptionWaitTime(option)
  1871. printLog(u"getOptionValue:获取到进入叶节点%s,等待时间为%s"%(option, waitTime))
  1872. time.sleep(waitTime)
  1873. time.sleep(0.5)
  1874. # 截图;
  1875. current_uiPic = self.getCurrentUIPath()
  1876. # 获取焦点框;
  1877. result, opcfg = self.tFocus.getOptionConfig(option, is_value_sheet)
  1878. if result is False:
  1879. self.redRat3.sendKey('return', option_data['layers'] + 1, 0.2)
  1880. print(u"getOptionValue.获取焦点参数失败")
  1881. return False, ''
  1882. dcfg = opcfg['dcfg']
  1883. icon_path = opcfg['icon_path']
  1884. icon_dir_path = opcfg['dir_path']
  1885. # 获取聚集框;
  1886. result, cur_box = self.tFocus.findFocusByIcon(current_uiPic, icon_path, dcfg)
  1887. if result is False:
  1888. self.redRat3.sendKey('return', option_data['layers'] + 1, 0.2)
  1889. print(u"getOptionValue.获取焦点框轮廓失败")
  1890. return False, ''
  1891. # 根据dir计算文本框;
  1892. cur_box = self.getFocusTextBox4(icon_dir_path, option, cur_box, is_value_sheet)
  1893. # 获取文本区域截图;
  1894. ocr_result_text = ''
  1895. txt_pic = os.path.join(getSATTmpDIR(), "meuttree_area_text.png")
  1896. self.imgCMP.saveCropPic(current_uiPic, txt_pic, (cur_box[0], cur_box[1], cur_box[2], cur_box[3]))
  1897. if is_value_sheet is True:
  1898. value_paramters = self.uitRunner.uitData.UITree.get_value(option, '')
  1899. isRangeType = False
  1900. # 判断设置值的类型 是rang类型还是str类型
  1901. if value_paramters['value_for_ocr'].__len__() and "range(" in value_paramters['value_for_ocr'][0].lower():
  1902. isRangeType = True
  1903. if isRangeType is True:
  1904. # 获取ocr列表;
  1905. hasOption,path = self.uitRunner.uitData.UITree.get_option(option)
  1906. if hasOption:
  1907. self.get_ocr_list(path['level'], option)
  1908. for orc_item in self.ocrDict:
  1909. # ocr_result = self.ocr.getStr(txt_pic, orc_item["lan"], orc_item["type"])
  1910. ocr_result = self.ocr.getStrWithImgProcess(txt_pic, thresholdDict, orc_item["lan"],
  1911. orc_item["type"],
  1912. reconTimes=1)
  1913. # print("getCurrentFocusOcr_Int=ocr识别结果=%s" % (ocr_result))
  1914. printLog("getCurrentFocusOcr_Int=ocr识别结果=%s" % (ocr_result))
  1915. if ocr_result == "ERR<Exp>" or ocr_result.__len__() == 0:
  1916. continue
  1917. # 字符串去掉末尾">"符号;
  1918. ocr_result = ocr_result.strip('>')
  1919. # 按数字分解多组文本;
  1920. list_ocr = getDigitFromString(ocr_result)
  1921. # list_ocr = self.strSplit(ocr_result)
  1922. # 只判断最后一位是否是数字;
  1923. if list_ocr.__len__() < 1:
  1924. errorPngName = "menutree_error_" + self.currentTime() + "ocr.png"
  1925. error_uiPic = os.path.join(getSATTmpDIR(), errorPngName)
  1926. self.ccard.takePicture(error_uiPic)
  1927. # print u"当前识别的ocr 不包含int类型值,截图为:%s" % (str(ocr_result))
  1928. printLog(u"当前识别的ocr 不包含int类型值,截图为:%s" % (str(ocr_result)))
  1929. continue
  1930. try:
  1931. # 获取最右边的文本,如果是数字则退出;
  1932. text_int_str = list_ocr[list_ocr.__len__() - 1]
  1933. # print 'text_int_str:', text_int_str
  1934. printLog('text_int_str:%s' % str(text_int_str))
  1935. ocr_result_text = float(text_int_str)
  1936. break
  1937. except Exception:
  1938. continue
  1939. else:
  1940. # 普通ocr文本识别;
  1941. # ocr_result_text = self.ocr.getStr(txt_pic, "ChinesePRC+English", 4)
  1942. ocr_result_text = self.ocr.getStrWithImgProcess(txt_pic, thresholdDict, "ENG", 10000,
  1943. reconTimes=1)
  1944. else:
  1945. # 普通ocr文本识别;
  1946. # ocr_result_text = self.ocr.getStr(txt_pic, "ChinesePRC+English", 4)
  1947. ocr_result_text = self.ocr.getStrWithImgProcess(txt_pic, thresholdDict, "ENG", 10000,
  1948. reconTimes=1)
  1949. # 退出菜单;
  1950. self.redRat3.sendKey('return', option_data['layers'] + 1, 0.2)
  1951. # 返回结果;
  1952. return True, ocr_result_text
  1953. def getParentWaitTime(self, parent):
  1954. optionName = parent + "WaitTime"
  1955. try:
  1956. waitTime = float(self.tconfig.get_value("waitTime", optionName))
  1957. except Exception:
  1958. waitTime = 1.0
  1959. # print "获取%s界面的等待界面时间失败,使用默认值1.0s" % str(parent)
  1960. return waitTime
  1961. def getOptionWaitTime(self, option):
  1962. result, option_data = self.uitRunner.uitData.UITree.get_option(option)
  1963. print u"getOptionWaitTime.option_data:",option_data
  1964. if result:
  1965. try:
  1966. others = json.loads(option_data['others'])
  1967. waitTime = float(others['waitTime'])
  1968. except Exception,e:
  1969. print u"获取%s界面的等待时间失败,使用默认值1.0s" % str(option)
  1970. waitTime = 1.0
  1971. else:
  1972. waitTime = 1.0
  1973. return waitTime
  1974. def getLeafWaitTime(self, option):
  1975. leaf_data = self.uitRunner.uitData.UITree.get_value(option)
  1976. print u"getLeafWaitTime.option_data:",leaf_data
  1977. try:
  1978. others = json.loads(leaf_data['others'])
  1979. waitTime = float(others['waitTime'])
  1980. except Exception,e:
  1981. print u"获取%s界面的等待时间失败,使用默认值1.0s" % str(option)
  1982. waitTime = 1.0
  1983. return waitTime
  1984. # channel_count:如果有频道,最大可能的频道数量;
  1985. # black_th:黑色频道背景色RGB单通道值
  1986. # black_rate:图片分割成100块,纯黑色区域占有比
  1987. def getBlackChannel(self, channel_count, black_th=20, black_rate=0.8):
  1988. result = False
  1989. # 根据频道数量遍历;
  1990. for i in range(0, channel_count):
  1991. pass
  1992. # 截图,取左半边;
  1993. pic_path = self.getCurrentUIPath()
  1994. img = cv.imread(pic_path)
  1995. pic_path2 = os.path.join(getSATTmpDIR(), "menutree_focus_area_half.png")
  1996. self.imgCMP.saveCropPic(pic_path, pic_path2, (0, 0, img.shape[1] / 2, img.shape[0]))
  1997. # 是否符合要求;
  1998. result = self.imgCMP.isBlack(pic_path2, black_th, 10, 1 - black_rate)
  1999. if result is True:
  2000. break
  2001. # 下一频道号;
  2002. self.redRat3.sendKey('C+')
  2003. time.sleep(4)
  2004. # endfor
  2005. return result
  2006. # 新增操作接口
  2007. # 聚焦到Option 区别于openOption,focusOption不会执行到option的子界面中
  2008. def focusOption(self, option, Max_Try=15):
  2009. # 切黑场;
  2010. self.sourceInput.setPattern(11)
  2011. # 获取menu path;
  2012. print u"focusOption start >>>"
  2013. path_params = self.uitPathManage.get_option_paths(option)
  2014. # print 'openOption=path_params:', path_params
  2015. printLog('focusOption=path_params:%s' % str(path_params))
  2016. checkRunOptionPathResult = self.uitPathManage.checkRunOptionPath(path_params)
  2017. if str(checkRunOptionPathResult) == "NoExit":
  2018. printLog(u"表格中不存在到达Option: %s 的路径,在表格中排查到达该Option路径" % str(option))
  2019. return False
  2020. if str(checkRunOptionPathResult) == "Fail":
  2021. printLog(u"表格中到达Option: %s 的路径出现数据断层找不到First层级,在表格中排查到达该Option路径" % str(option))
  2022. return False
  2023. runPathCount = 0
  2024. pathCount = path_params.__len__()
  2025. printLog("focusOption=pathCount:%s" % str(pathCount))
  2026. # returnKeyEventCount = path_params.__len__() + 1
  2027. returnKeyEventCount = 0
  2028. print "returnKeyEventCount:", returnKeyEventCount
  2029. printLog("focusOption=returnKeyEventCount:%s" % str(returnKeyEventCount))
  2030. # 逆序路径key;
  2031. revpp = reversed(path_params)
  2032. # 根节点是否已进入;
  2033. entry = False
  2034. first_parent = u''
  2035. first_option = u''
  2036. # 遍历路径(已排序,从first开始);
  2037. # print "revpp:", revpp
  2038. printLog("focusOption=revpp:%s" % str(revpp))
  2039. for level in revpp:
  2040. # print "openOption=level:", path_params[level]
  2041. printLog("focusOption=level:", path_params[level])
  2042. # 是否进入根结点;
  2043. if entry == False:
  2044. # 标记已进入根;
  2045. entry = True
  2046. first_parent = path_params[level]["parent"]
  2047. first_option = path_params[level]["option"]
  2048. checkFirstOptionTimes = 0
  2049. while True:
  2050. if checkFirstOptionTimes > 2:
  2051. printLog(u"focusOption=尝试3次快捷按键没有唤出聚焦焦点界面!!!")
  2052. return False
  2053. printLog(u"第%s次尝试呼出一级界面" % str(checkFirstOptionTimes))
  2054. # # 进入根节点(根节点名就是遥控键名);
  2055. # self.redRat3.sendKey(path_params[level]["parent"])
  2056. # 判断是否存在others字段,others字段中存在first_key,则优先使用first_key进入
  2057. try:
  2058. others = json.loads(path_params[level]["others"])
  2059. except Exception,e:
  2060. others = {}
  2061. printLog("section others:%s"%others)
  2062. if "first_key" in others.keys():
  2063. first_key = others["first_key"]
  2064. else:
  2065. first_key = path_params[level]["parent"]
  2066. printLog(u"进入根节点,first_key:%s"%first_key)
  2067. # 进入根节点
  2068. self.redRat3.sendKey(first_key)
  2069. waitTime = self.getParentWaitTime(path_params[level]["parent"])
  2070. printLog(u"打开%s界面的等待时间waittime为:%s" % (str(path_params[level]["parent"]), str(waitTime)))
  2071. time.sleep(waitTime)
  2072. # 获取ocr列表;
  2073. self.get_ocr_list(level, option)
  2074. if self.isFirstOptionShow(level, first_parent, first_option):
  2075. printLog(u"呼出一级菜单界面")
  2076. break
  2077. else:
  2078. time.sleep(5)
  2079. self.redRat3.sendKey("return", 2)
  2080. checkFirstOptionTimes = checkFirstOptionTimes + 1
  2081. # 如果一级界面弹出成功,则退出时候返回按键次数加1
  2082. returnKeyEventCount = returnKeyEventCount + 1
  2083. # 如果 others 字段不为空;
  2084. if path_params[level]["others"].__len__():
  2085. # 如果不是跑马灯处理则按照输入密码处理
  2086. if self.dealOthers(level, path_params[level]) is True:
  2087. # print u"解锁失败!!!"
  2088. printLog(u"focusOption=解锁失败!!!")
  2089. return False
  2090. # 移动到子节点;
  2091. cur_option_enter_key = path_params[level]["option_enter_key"]
  2092. # 移动到子节点;
  2093. if cur_option_enter_key.__len__() == 0:
  2094. enter_key = path_params[level]["enter_key"]
  2095. else:
  2096. enter_key = cur_option_enter_key
  2097. move_key = path_params[level]["move_key"]
  2098. if str(move_key) == str([u'up', u'down']) or str(move_key) == str([u'down', u'up']):
  2099. findDirection = str(move_key[1])
  2100. elif str(move_key) == str([u'left', u'right']) or str(move_key) == str([u'right', u'left']):
  2101. findDirection = str(move_key[1])
  2102. else:
  2103. findDirection = 'grid'
  2104. result = self.move2TargetNode(
  2105. level,
  2106. first_parent,
  2107. path_params[level],
  2108. returnKeyEventCount,
  2109. findDirection=findDirection, Max_Try=Max_Try)
  2110. if result is True:
  2111. runPathCount = runPathCount + 1
  2112. printLog("focusOption=runPathCount:%s" % str(runPathCount))
  2113. if runPathCount == pathCount:
  2114. print u"执行到最后一级"
  2115. pass
  2116. else:
  2117. # 子节点的进入方式默认为ok;
  2118. self.redRat3.sendKey(enter_key)
  2119. # 如果执行一次enter_key,则退出时按返回键的次数加一
  2120. if enter_key != u'default':
  2121. returnKeyEventCount = returnKeyEventCount + 1
  2122. else:
  2123. print "focusOption end<<<<"
  2124. return False
  2125. # end-for
  2126. print "focusOption end <<<<"
  2127. return True
  2128. # 假定已经在option所在的页面,逐步移动到目标option,聚焦到option
  2129. def moveToOption(self, option, Max_Try=15):
  2130. # 切黑场;
  2131. # self.sourceInput.setPattern(11)
  2132. # 获取menu path;
  2133. print "moveToOption start >>>"
  2134. path_params = self.uitPathManage.get_option_paths(option)
  2135. # print 'openOption=path_params:', path_params
  2136. printLog('moveToOption=path_params:%s' % str(path_params))
  2137. checkRunOptionPathResult = self.uitPathManage.checkRunOptionPath(path_params)
  2138. if str(checkRunOptionPathResult) == "NoExit":
  2139. printLog(u"表格中不存在到达Option: %s 的路径,在表格中排查到达该Option路径" % str(option))
  2140. return False
  2141. if str(checkRunOptionPathResult) == "Fail":
  2142. printLog(u"表格中到达Option: %s 的路径出现数据断层找不到First层级,在表格中排查到达该Option路径" % str(option))
  2143. return False
  2144. runPathCount = 0
  2145. pathCount = path_params.__len__()
  2146. printLog("moveToOption=pathCount:%s" % str(pathCount))
  2147. returnKeyEventCount = path_params.__len__()
  2148. # print "returnKeyEventCount:", returnKeyEventCount
  2149. printLog("moveToOption=returnKeyEventCount:%s" % str(returnKeyEventCount))
  2150. # 逆序路径key;
  2151. revpp = reversed(path_params)
  2152. # 根节点是否已进入;
  2153. entry = False
  2154. first_parent = u''
  2155. # first_option = u''
  2156. # 遍历路径(已排序,从first开始);
  2157. # print "revpp:", revpp
  2158. printLog("moveToOption=revpp:%s" % str(revpp))
  2159. for level in revpp:
  2160. # print "openOption=level:", path_params[level]
  2161. runPathCount = runPathCount + 1
  2162. print "level:", level, type(level)
  2163. print "runPathCount:", runPathCount, type(runPathCount)
  2164. print "pathCount:", pathCount, type(pathCount)
  2165. printLog("openOption=level:", path_params[level])
  2166. # 是否进入根结点;
  2167. if entry == False:
  2168. # 标记已进入根;
  2169. entry = True
  2170. first_parent = path_params[level]["parent"]
  2171. # 由于已经到达option同级界面,只执行最后一层
  2172. if runPathCount == pathCount:
  2173. # 移动到子节点;
  2174. cur_option_enter_key = path_params[level]["option_enter_key"]
  2175. # 移动到子节点;
  2176. if cur_option_enter_key.__len__() == 0:
  2177. enter_key = path_params[level]["enter_key"]
  2178. else:
  2179. enter_key = cur_option_enter_key
  2180. move_key = path_params[level]["move_key"]
  2181. if str(move_key) == str([u'up', u'down']) or str(move_key) == str([u'down', u'up']):
  2182. findDirection = str(move_key[1])
  2183. elif str(move_key) == str([u'left', u'right']) or str(move_key) == str([u'right', u'left']):
  2184. findDirection = str(move_key[1])
  2185. else:
  2186. findDirection = 'grid'
  2187. result = self.move2TargetNode(
  2188. level,
  2189. first_parent,
  2190. path_params[level],
  2191. returnKeyEventCount,
  2192. findDirection=findDirection, Max_Try=Max_Try)
  2193. if result is True:
  2194. # runPathCount = runPathCount+1
  2195. printLog("moveToOption=runPathCount:%s" % str(runPathCount))
  2196. if runPathCount == pathCount:
  2197. print "执行到最后一级"
  2198. pass
  2199. else:
  2200. # 子节点的进入方式默认为ok;
  2201. self.redRat3.sendKey(enter_key)
  2202. else:
  2203. print "moveToOption end<<<<"
  2204. return False
  2205. # end-for
  2206. print "moveToOption end <<<<"
  2207. return True
  2208. # 找到两个字符串左边或者右边相同的部分
  2209. def findDuplicateString(self, str1, str2, direction="right"):
  2210. index = 0
  2211. if direction == "right":
  2212. while True:
  2213. index -= 1
  2214. if abs(index) > str1.__len__() or abs(index) > str2.__len__():
  2215. break
  2216. if not str1[index] == str2[index]:
  2217. break
  2218. if index == -1:
  2219. return ""
  2220. return str1[index+1:]
  2221. elif direction == "left":
  2222. while True:
  2223. if abs(index) >= str1.__len__() or abs(index) >= str2.__len__():
  2224. break
  2225. if not str1[index] == str2[index]:
  2226. break
  2227. index += 1
  2228. return str1[:index]
  2229. # 去掉字符串数组中每个字符串 左边或右边相同的部分
  2230. def removeDuplicateString(self, strList):
  2231. finishedList = strList
  2232. directionList = ["left", "right"]
  2233. for direction in directionList:
  2234. same_str = self.findDuplicateString(strList[0], strList[1], direction)
  2235. if same_str == "":
  2236. continue
  2237. else:
  2238. for i in range(2, strList.__len__()):
  2239. same_str = self.findDuplicateString(same_str,strList[i], direction)
  2240. if same_str == "":
  2241. break
  2242. if same_str != "":
  2243. finishedList = []
  2244. for str in strList:
  2245. if direction == "left":
  2246. str = str[same_str.__len__():]
  2247. else:
  2248. str = str[:-same_str.__len__()]
  2249. finishedList.append(str)
  2250. return finishedList
  2251. if __name__ == "__main__":
  2252. tmenu = CTMenu()
  2253. print "执行开始!"
  2254. # ThresholdDict = tmenu.tconfig.getThresholdDict("factory")
  2255. # ThresholdDict = tmenu.tconfig.getThresholdDict("setting")
  2256. # print "ThresholdDict:", ThresholdDict, type(ThresholdDict)
  2257. # tmenu.getOptionValue("picture_preset")value
  2258. # parent_ocr_dict = tmenu.xlsparser.get_parent_ocr_dict("automatic_search_analogue")
  2259. # print "parent_ocr_dict:",parent_ocr_dict
  2260. # 获取menu path;
  2261. # value_params, path_params = tmenu.xlsparser.get_menu_paths('av', '')
  2262. # print value_params, path_params
  2263. # tmenu.redRat3.sendKey('home')
  2264. # tmenu.move2TargetGridNode_matchTemp('First', 'home', path_params['First'], 1)
  2265. # isSuccessed = tmenu.setOptionValue("picture_preset", "stadium")
  2266. # isSuccessed = tmenu.setOptionValue("backlight", 50)
  2267. # isSuccessed = tmenu.checkOptionValue("picture_preset", "stadium")
  2268. # isSuccessed = tmenu.checkOptionValue("backlight", 50)
  2269. # print u'isSuccessed:', isSuccessed
  2270. # isSuccessed_focusOption = tmenu.focusOption("picture_preset")
  2271. # print u'聚焦到目标Option:auto_volume_control 结果isSuccessed_focusOption:', isSuccessed_focusOption
  2272. # 确保当前焦点是在目标Option同级的
  2273. # if isSuccessed_focusOption:
  2274. # isSuccessed_moveToOption = tmenu.moveToOption("picture_reset")
  2275. # print u'焦点移动到目标Option结果isSuccessed_moveToOption:', isSuccessed_moveToOption
  2276. # value_params, path_params = tmenu.xlsparser.get_menu_paths("picture_preset ", "personal")
  2277. # print "value_params:",value_params
  2278. # print "path_params:",path_params
  2279. #
  2280. # path_params_1 = tmenu.xlsparser.get_option_paths("picture_preset ")
  2281. # print "path_params_1:", path_params_1
  2282. # isHasValue, ocr_result_text = tmenu.getOptionValue("backlight")
  2283. # print "isHasValue:",isHasValue,type(isHasValue)
  2284. # print "ocr_result_text:",ocr_result_text,type(ocr_result_text)
  2285. # tmenu.setOptionValue("backlight",ocr_result_text)
  2286. # paths = tmenu.xlsparser.get_option_paths('usb')
  2287. # tmenu.move2TargetGridNode('first', 'usb', paths, 5)
  2288. # isSuccessed = tmenu.setOptionValue("source", "tv")
  2289. # isSuccessed = tmenu.setOptionValue("picture_preset", "stadium")
  2290. # isSuccessed = tmenu.setOptionValue("picture_preset", "dynamic")
  2291. # isSuccessed = tmenu.setOptionValue("gamma", 0)
  2292. # isSuccessed = tmenu.setOptionValue("instant_power_on", "on")
  2293. # isSuccessed = tmenu.setOptionValue("RGB_mode", "green_only")
  2294. # isSuccessed = tmenu.focusOptionValue("option", "enjoy_music")
  2295. # print "isSuccessed:", isSuccessed
  2296. # settingWaitTime = tmenu.getParentWaitTime("setting")
  2297. # print settingWaitTime
  2298. # sourceWaitTime = tmenu.getParentWaitTime("source")
  2299. # print sourceWaitTime
  2300. # print tmenu.setOptionValue('overscan', 'off')
  2301. # print tmenu.getOptionValue('overscan')
  2302. # settings 检测焦点选择类的setOptionValue
  2303. # isSuccessed = tmenu.setOptionValue("backlight", 50)
  2304. # print "isSuccessed:", isSuccessed
  2305. # isSuccessed = tmenu.setOptionValue("500hz", 50)
  2306. # print u'isSuccessed:', isSuccessed
  2307. # settings 检测值设置类的setOptionValue
  2308. # isSuccessed = tmenu.setOptionValue("backlight", 70)
  2309. # isSuccessed = tmenu.setOptionValue("auto_volume_control", "on")
  2310. # print u'isSuccessed:', isSuccessed
  2311. # settings 检测焦点选择类的checkOptionValue
  2312. # isSuccessed = tmenu.checkOptionValue("picture_preset", "movie")
  2313. # print u'isSuccessed:', isSuccessed
  2314. # isSuccessed = tmenu.setOptionValue("picture_preset", "movie", leafNodeValueWaitTime=2.0)
  2315. # print u'isSuccessed:', isSuccessed
  2316. # settings 检测值设置类的checkOptionValue
  2317. # isSuccessed = tmenu.checkOptionValue("backlight", 70)
  2318. # print u'isSuccessed:', isSuccessed
  2319. # 信源切换检测
  2320. # isSuccessed = tmenu.setSourceValue('source', 'hdmi2', sourceWaitTime=1.5)
  2321. # print u'进入信源(hdmi2)isSuccessed:', isSuccessed
  2322. # isSuccessed = tmenu.setSourceValue('source', 'av')
  2323. # print u'进入信源(tv)isSuccessed:', isSuccessed
  2324. # 频道列表检测
  2325. # checkResult,failChannelList=tmenu.checkChannelList(["6", "22"])
  2326. # print u'checkResult,failChannelList:', checkResult,failChannelList
  2327. # 检测自动搜台
  2328. # isSuccessed = tmenu.auto_search("automatic_search",[["as_tuner_mode","air"],["as_channel_type","analog"]])
  2329. # print u'isSuccessed:', isSuccessed
  2330. # isSuccessed =tmenu.auto_search("automatic_search", [["as_tuner_mode", "air"], ["as_channel_type", "analog"]],
  2331. # ["as_search", "finished"])
  2332. # print u'isSuccessed:', isSuccessed
  2333. # 检测手动搜台
  2334. # isSuccessed =tmenu.manual_search("manual_tuning", [["mt_tuner_mode", "air"], ["mt_channel_type", "analog"], ["mt_ch", 12]])
  2335. # print u'isSuccessed:', isSuccessed
  2336. # isSuccessed = tmenu.manual_search("manual_tuning",
  2337. # [["mt_tuner_mode", "cable"], ["mt_channel_type", "digital"], ["mt_ch", 12]])
  2338. # print u'isSuccessed:', isSuccessed