SomkePretreatment.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. # -*- coding:utf-8 -*-
  2. import os
  3. import sys
  4. import time
  5. import re
  6. # import getopt
  7. import json
  8. import chardet
  9. import datetime
  10. import hashlib # md5验证;
  11. import subprocess
  12. import urllib2
  13. import threading
  14. from ssat_sdk.basessh2 import baseSSH2
  15. from ssat_sdk.tv_operator import TvOperator
  16. # 导入测试精灵;
  17. from ssat_sdk.device_manage.testWizardClient import TestWizardClient
  18. from SATClient import SATClient
  19. # 导入http相关库:python2.x中2个一起用,python3.x合并成一个urllib
  20. import urllib
  21. import urllib2
  22. class SomkePretreatment:
  23. def __init__(self, taskId=None):
  24. self.taskId = taskId
  25. if self.taskId is None:
  26. self.__parseCommandLine()
  27. # 任务信息;
  28. self.taskInfo = {}
  29. self.ota_local_name = 'usb_ota.zip'
  30. # 上传升级包的位置;
  31. # self.updateZip = ' /storage/0000-0000/usb_ota.zip'
  32. self.updateZip = ' /storage/905A-30AB/usb_ota.zip'
  33. # ota路径;
  34. self.ota_server_path = "/home/RT2841_2851_dailybuild/DailyBuild_RT2841_%s/" % str(time.strftime("%m%d"))
  35. # ota名称;
  36. self.ota_server_name = 'signed-ota_rt2841_update.zip'
  37. # apk安装ota的命令;
  38. self.installCmd = ' shell am start -n com.apps.ota/.ui.MainActivity'
  39. # ssh2;
  40. self.ssh2 = baseSSH2()
  41. # 遥控器;
  42. self.redhat3 = TvOperator()
  43. # 获取任务信息;
  44. self.getTaskInfo()
  45. '''
  46. 函数:解析命令行参数
  47. 参数:
  48. 返回:
  49. 注意:argv[0]属于程序本身名称
  50. '''
  51. def __parseCommandLine(self):
  52. if sys.argv.__len__() > 1:
  53. try:
  54. args = json.loads(sys.argv[1].replace("'", '"'))
  55. # 解析出taskId;
  56. if "TaskId" in args:
  57. self.taskId = args["TaskId"]
  58. print "TaskId=", self.taskId
  59. except Exception, e:
  60. print u"解析json失败:%s" % sys.argv[1]
  61. def __cmdExecute(self, cmd):
  62. # 定义文件名称;
  63. file_name = str(time.time())
  64. # 输出到文件中;
  65. cmd = cmd + ' >> ' + file_name
  66. print u'执行cmd:', cmd
  67. proc = subprocess.Popen(cmd, shell=True)
  68. # 等待完成;
  69. proc.wait()
  70. # 读取文件内容;
  71. data = ''
  72. with open(file_name, mode="rb") as f:
  73. data = f.read()
  74. os.remove(file_name)
  75. print u"cmd结果:", data
  76. return data
  77. def __adbConnect(self):
  78. try:
  79. # 启用adb的root权限;
  80. cmd = "adb connect " + self.taskInfo["deviceSerial"]
  81. proc = self.__cmdExecute(cmd)
  82. if proc.find("connected to " + self.taskInfo["deviceSerial"] + ":5555") < 0 and proc.find(
  83. "already connected to " + self.taskInfo["deviceSerial"] + ":5555") < 0:
  84. return False
  85. print "adb connect success"
  86. return True
  87. except Exception, e:
  88. print 'adb connect error:', e
  89. return False
  90. def adbCheck(self):
  91. try:
  92. cmd = "adb devices"
  93. proc = self.__cmdExecute(cmd)
  94. if proc.find(self.taskInfo["deviceSerial"] + ":5555\tdevice\r\n") > -1:
  95. print "adb connected"
  96. return True
  97. print "adb didn't connected"
  98. return False
  99. except Exception,e:
  100. return False
  101. def __adbDisconnect(self):
  102. # 启用adb的root权限;
  103. cmd = "adb disconnect " + self.taskInfo["deviceSerial"]
  104. proc = self.__cmdExecute(cmd)
  105. if proc.find("disconnected " + self.taskInfo["deviceSerial"]) < 0 and proc.find(
  106. "error: no such device '" + self.taskInfo["deviceSerial"] + ":5555'") < 0:
  107. return False
  108. print "adb disConnect success"
  109. return True
  110. def __adbRoot(self):
  111. try:
  112. # 启用adb的root权限;
  113. cmd = "adb -s " + self.taskInfo["deviceSerial"] + " root"
  114. proc = self.__cmdExecute(cmd)
  115. if proc.find("adbd is already running as root") < 0 and proc.find(
  116. "restarting adbd as root") < 0 and proc != '':
  117. return False
  118. print "adb root success"
  119. return True
  120. except Exception, e:
  121. print 'adb root error:', e
  122. return False
  123. def __adbRemount(self):
  124. # 启用adb的root权限;
  125. cmd = "adb -s " + self.taskInfo["deviceSerial"] + " remount /data"
  126. proc = self.__cmdExecute(cmd)
  127. if proc.find("adbd is already running as root") < 0 and proc.find("restarting adbd as root") < 0 and proc != '':
  128. return False
  129. print "adb root success"
  130. return True
  131. def __adbInstallApk(self, apk_path):
  132. if os.path.exists(apk_path):
  133. cmd = 'adb -s ' + self.taskInfo['deviceSerial'] + ' install -r -t ' + apk_path
  134. proc = self.__cmdExecute(cmd)
  135. if (proc.find('Success') >= 0):
  136. print "install ota_install.apk success"
  137. # 启动app;
  138. cmd = 'adb -s ' + self.taskInfo[
  139. 'deviceSerial'] + r' shell am start -n com.apps.ota.myapplication/.DeleteZipActivity'
  140. proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True).communicate()[
  141. 0]
  142. return True
  143. return False
  144. def __adbUninstallApk(self, apk_name):
  145. return False
  146. def __requestTaskInfo(self):
  147. # 请求服务器;
  148. data = {'data':{"taskId" : self.taskId}}
  149. msg = {'requestMsg' : json.dumps(data)}
  150. try:
  151. post_data = urllib.urlencode(msg)
  152. url = 'http://10.126.16.60:8580/btc_task_se/ajaxExternalInteractiveManage!getSmokeTaskInfo.action'
  153. response = urllib2.urlopen(url, post_data)
  154. data = response.read().decode("utf-8")
  155. res = json.loads(data)
  156. if str(res['responseMsg']['code']) == '00':
  157. self.taskInfo = {
  158. "host": res['responseMsg']['data']['compileInfo']['serverName'],
  159. "hostPort": res['responseMsg']['data']['compileInfo']['serverPort'],
  160. "hostUser": res['responseMsg']['data']['compileInfo']['serverAccount'],
  161. "hostPwd": res['responseMsg']['data']['compileInfo']['serverPassword'],
  162. "deviceSerial": res['responseMsg']['data']['deviceId']
  163. }
  164. # 服务器路径;
  165. ser_path = res['responseMsg']['data']['compileInfo']['resultPath']
  166. self.ota_server_path = "%sDailyBuild_RT2841_%s/" % (ser_path, str(time.strftime("%m%d")))
  167. print u"taskInfo",self.taskInfo
  168. print u"ser_path",ser_path
  169. print u"ota_server_path", self.ota_server_path
  170. # 返回结果;
  171. return True
  172. except Exception, e:
  173. print u"获取任务信息失败",e
  174. # 默认返回False
  175. return False
  176. def getWindowsUsbPath(self):
  177. disks = self.__cmdExecute("wmic logicaldisk get deviceid, description")
  178. print chardet.detect(disks)
  179. disks = disks.decode("utf-16").encode('utf-8').decode('utf-8-sig')
  180. disks = disks.split('\r\n')
  181. for disk in disks:
  182. if u'可移动磁盘' in disk:
  183. return re.search(r'\w:', disk).group()
  184. return None
  185. '''
  186. 函数:获取任务信息;
  187. 参数:
  188. 返回:
  189. '''
  190. def getTaskInfo(self):
  191. # 任务信息;
  192. if self.taskId is None or self.taskInfo.__len__() == 0: #测试开关;
  193. self.taskId = 5520
  194. self.taskInfo = {
  195. "host": "10.201.251.254",
  196. "hostPort": 22,
  197. "hostUser": "wjf",
  198. "hostPwd": "wjf2019",
  199. "deviceSerial": '192.168.18.210'
  200. }
  201. # 请求服务器;
  202. if self.__requestTaskInfo() is False:
  203. return
  204. # 初始化ssh2;
  205. self.ssh2.init_ssh2(self.taskInfo['hostUser'], self.taskInfo['hostPwd'], self.taskInfo['host'], self.taskInfo['hostPort'])
  206. self.redhat3.sendKey('home')
  207. self.redhat3.sendKey('home')
  208. self.__adbConnect()
  209. '''
  210. 函数:下载apk
  211. 参数:
  212. 返回:
  213. '''
  214. def downloadApk(self, apk_url, save_path):
  215. pass
  216. '''
  217. 函数:apk是否已在本地;
  218. 参数:
  219. 返回:
  220. '''
  221. def isApkExist(self, apk_md5, apk_path):
  222. local_md5 = ''
  223. file_data = []
  224. md5_local = hashlib.md5()
  225. if os.path.exists(apk_path):
  226. with open(apk_path, mode='rb') as f:
  227. while True:
  228. data = f.read(8192)
  229. if not data:
  230. break
  231. md5_local.update(data)
  232. local_md5 = md5_local.hexdigest()
  233. print u"本地MD5=", local_md5
  234. return True if apk_md5 == local_md5 else False
  235. def installApk(self, apk_path):
  236. # 先连接才能root;
  237. if self.__adbConnect() is False:
  238. return False
  239. # 安装apk
  240. if self.__adbInstallApk(apk_path) is False:
  241. return False
  242. # 断开adb连接;
  243. # self.__adbDisconnect()
  244. return True
  245. def unInstallApk(self, apk_name):
  246. # 先连接才能root;
  247. if self.__adbConnect() is False:
  248. return
  249. # 启用adb的root权限;
  250. if self.__adbRoot() is False:
  251. return
  252. if self.__adbUninstallApk(apk_name) is False:
  253. return
  254. def parseOTAImageName(self):
  255. pass
  256. def isOTAImageOnServer(self):
  257. cmd = "ls %s" % self.ota_server_path
  258. status, data = self.ssh2.execute_cmd(cmd)
  259. if status is True and data.find(self.ota_server_name) >= 0:
  260. return True
  261. return False
  262. def downloadOTAImage(self):
  263. print u"downloadOTAImage start"
  264. sftp_path = self.ota_server_path + self.ota_server_name
  265. usbSwitch = TestWizardClient()
  266. '''
  267. 尝试5次切换U盘
  268. '''
  269. tryCount = 5
  270. switchRet = False
  271. while tryCount > 0:
  272. if usbSwitch.sendUsbSwitch(1) is True:
  273. switchRet = True
  274. break
  275. time.sleep(2)
  276. tryCount = tryCount - 1
  277. if switchRet is False:
  278. print u"切换U盘到电脑失败"
  279. return False
  280. time.sleep(5) # 等待Windows识别U盘。
  281. usbPath = self.getWindowsUsbPath()
  282. if usbPath is None:
  283. print u"获取U盘盘符失败"
  284. return False
  285. local_path = usbPath + "\\" + self.ota_local_name
  286. return self.ssh2.sftp_download_md5(sftp_path, local_path)
  287. def isOTAImageOnLocal(self):
  288. pass
  289. def uploadOTAImage2TV(self):
  290. # 必须先root才能push;
  291. if self.__adbRoot() is False:
  292. print u"adb root失败"
  293. return False
  294. '''
  295. 尝试5次切换U盘
  296. '''
  297. tryCount = 5
  298. switchRet = False
  299. usbSwitch = TestWizardClient()
  300. while tryCount > 0:
  301. if usbSwitch.sendUsbSwitch(0) is True:
  302. switchRet = True
  303. break
  304. time.sleep(2)
  305. tryCount = tryCount - 1
  306. if switchRet is False:
  307. print u"切换U盘到TV失败"
  308. return False
  309. return True
  310. def reomveOTAImageOnTV(self):
  311. pass
  312. def installOTAImage(self):
  313. print u"installOTAImage start"
  314. try:
  315. self.redhat3.sendKey("home")
  316. cmd = 'adb -s ' + self.taskInfo['deviceSerial'] + self.installCmd
  317. proc = self.__cmdExecute(cmd)
  318. print proc
  319. self.redhat3.sendKey("down")
  320. time.sleep(1.5)
  321. self.redhat3.sendKey("ok")
  322. time.sleep(1.5)
  323. self.redhat3.sendKey("ok")
  324. # 等待60秒启动安装;
  325. time.sleep(60)
  326. except Exception, e:
  327. print u'安装失败=', e
  328. def checkOTAInstall(self):
  329. try:
  330. # 先connect,再devices
  331. cmd = 'adb connect ' + self.taskInfo['deviceSerial']
  332. proc = self.__cmdExecute(cmd)
  333. if proc.find('connected') >= 0:
  334. cmd = 'adb devices'
  335. proc = self.__cmdExecute(cmd)
  336. if proc.find(self.taskInfo['deviceSerial'] + ':5555\tdevice') >= 0:
  337. print "device connect success"
  338. print "OTA update success!"
  339. return True
  340. time.sleep(10)
  341. return False
  342. except Exception, e:
  343. print u'检测失败=', e
  344. def initAtx(self):
  345. # 重启后,重连adb;
  346. client = SATClient()
  347. if client.send_add_device(self.taskInfo['deviceSerial']) is False:
  348. print u"重连adb设备失败",self.taskInfo['deviceSerial']
  349. self.__adbConnect()
  350. # 等待10;
  351. print "等待30秒,让TV完全启动。"
  352. time.sleep(30)
  353. os.system(r'D:\SAT\tools\atx-init\atx-init.bat')
  354. def turnOnTV(self):
  355. tryCount = 5
  356. while tryCount > 0:
  357. if self.adbCheck() is True:
  358. print u'开机成功'
  359. return True
  360. # 按下Power键;
  361. self.redhat3.sendKey("POWER")
  362. # 等待60秒;
  363. time.sleep(60)
  364. tryCount = tryCount -1
  365. # 尝试连接;
  366. self.__adbConnect()
  367. print u'开机失败'
  368. return False
  369. if __name__ == "__main__":
  370. smp = SomkePretreatment()
  371. smp.getTaskInfo()
  372. smp.adbCheck()
  373. # print smp.getWindowsUsbPath()
  374. # if smp.isOTAImageOnServer():
  375. # if smp.downloadOTAImage():
  376. # print u'下载完成'
  377. # else:
  378. # print u'下载失败'
  379. # smp.taskInfo = {"deviceSerial":'192.168.1.101'}
  380. # #if smp.installApk('F:\SAT\SAT_Runner\ota_apk\RT2841\ota_install.apk') is True:
  381. # #if smp.uploadOTAImage2TV('F:\signed-ota_rt2841_update.zip') is True:
  382. # smp.installOTAImage()
  383. # time.sleep(30)
  384. # upStatus = False
  385. # for i in range(30):
  386. # if smp.checkOTAInstall() is True:
  387. # upStatus = True
  388. # break
  389. # if upStatus is False:
  390. # print "OTA update time out 15min"