1# encoding=utf-8
2
3'''
4Created on 20181019
5
6@author: wangqi10
7@modify data:20200424
8@modify:update for BlueArea
9'''
10import platform
11import sys
12import threading
13import time
14import os
15import platform
16
17from util.time_info import get_now_time_str_info, get_now_time_info, Timeout, timeout
18from aw.Param.UpgradeParam import getAllParam
19from aw.Common.Constant import CONSTANT
20from util.log_info import logger
21
22def start(param):
23    '''
24    #===================================================================================
25    #   @Method:        start(param)
26    #   @Precondition:  none
27    #   @Func:          全流程执行模板:1.组合app执行顺序
28    #                                 2.初始化app,调用app.excute方法
29    #                                 3.返回app执行结果
30    #   @PostStatus:    none
31    #   @Param:         param:用户传递的参数列表
32    #   @eg:            start()
33    #   @return:        None
34    #===================================================================================
35    '''
36    if isinstance(param, dict):
37        logger.switchFilePath(param.get("logFilePath"))
38        runstage = param.get("runstage")
39        if runstage == "":
40            CONSTANT.ENVERRMESSAGE = "no runstage"
41            return -1
42        step_list = runstage.split(",")
43        param["step_list"] = step_list
44        system_type = platform.system()
45        for step in step_list:
46            app_name = step
47            app_pyFile = 'func.' + app_name[0: app_name.find('_')] + '.' + app_name
48            #app_class_name = app_name[0: app_name.rfind('_')].capitalize()
49            app_class_name = app_name[0: app_name.rfind('_')]
50            improt_cmd_str = 'from %s import %s as APP' % (app_pyFile, app_class_name)
51            print(improt_cmd_str)
52            logger.info("import_cmd_str:%s" % improt_cmd_str)
53            scope = {}
54            exec(improt_cmd_str, scope)
55            APP = scope.get('APP', 'none')
56            logger.info("APP:%s" % APP)
57            app = APP(param)
58            errorcode = app._excuteApp('upgrade')
59            time.sleep(5)
60            scriptpath =os.path.dirname(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
61            if system_type == "Windows":
62                loader_tool_path = os.path.join(scriptpath, "resource", "RK3568_tool", "upgrade_tool.exe")
63            else:
64                loader_tool_path = os.path.join(scriptpath, "resource", "RK3568_tool", "upgrade_tool")
65            logger.info(loader_tool_path)
66#           mycmd = "%s LD" % loader_tool_path
67#            try:
68#                num = send_cmd(mycmd)
69#                if num != 2:
70#                    logger.info("try again!")
71#                    time.sleep(40)
72#                    num = send_cmd(mycmd)
73#                    if num != 2:
74#                        logger.error("有设备断连,全部处置为真隔离状态!")
75#                        errorcode = 200
76#            except Exception as f:
77#               logger.error(f)
78#            logger.info(errorcode)
79            if errorcode == 99:
80                logger.error("upgrade success ,but Smoke failed, the fatal problem occurs.")
81                return 99
82            if errorcode == 98:
83                logger.error("upgrade success ,but Smoke failed, the key problem occurs.")
84                return 98
85            if errorcode == -1:
86                logger.error("upgrade failed.")
87                return 101
88            if errorcode == 200:
89                return -1
90            return 0
91        return 0
92    CONSTANT.ENVERRMESSAGE = "unknown error,please contact the engineer"
93    return -1
94
95
96def send_cmd(mycmd):
97    result = "".join(os.popen(mycmd).readlines())
98    logger.info(result)
99    num = int(result.split("(")[1].split(")")[0])
100    logger.info(num)
101    return num
102
103
104def parseProperties(param_file):
105    '''
106    #===================================================================================
107    #   @Method:        parseProperties(param_file)
108    #   @Precondition:  none
109    #   @Func:          将xxx.properties文件解析成start(param)方法中param参数需要的格式
110    #   @PostStatus:    none
111    #   @Param:         param:用户传递的参数列表
112    #   @eg:            parseProperties()
113    #   @return:        None
114    #===================================================================================
115    '''
116    param_dict = getAllParam(param_file)
117
118    #获取taskid
119    taskid = "NoTaskidJob"
120    task_path = param_file.split('.')[0]
121    if task_path.rfind("/") > -1:
122        r = task_path.rfind("/")
123    else:
124        r = task_path.rfind("\\")
125    taskid = task_path[r + 1:]
126
127    param_dict["taskId"] = taskid
128    param_dict["logFilePath"] = ''.join([task_path, ".log"])
129
130    return param_dict
131
132
133def saveSuccessVersion(success_version):
134    '''
135    #===================================================================================
136    #   @Method:        saveSuccessVersion(param_file)
137    #   @Precondition:  none
138    #   @Func:          存储成功的版本
139    #   @PostStatus:    none
140    #   @Param:         param:用户传递的参数列表
141    #   @return:        None
142    #===================================================================================
143    '''
144    save_path = CONSTANT.Path.getSavePath()
145    try:
146        with open(save_path, 'w') as f:
147            f.write(f'upgrade_upgradeLocation={success_version}')
148    except:
149        logger.info('save success version fail')
150    logger.info('saving success')
151
152
153def send_times(mycmd):
154    times = 0
155    outcome = sendCmd(mycmd)
156    while times < 3:
157        if not outcome or "Empty" in outcome:
158            times += 1
159            time.sleep(3)
160        else:
161            return outcome
162    return outcome
163
164
165def sendCmd(mycmd):
166    result = "".join(os.popen(mycmd).readlines())
167    return result
168
169
170@timeout(30)
171def hdc_kill():
172    logger.info("kill the process")
173    os.system("hdc_std kill")
174    time.sleep(5)
175    logger.info("start the process")
176    os.system("hdc_std start")
177    time.sleep(10)