TMenu.py 126 KB

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