TMenu.py 126 KB

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