TMenu.py 124 KB

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