1ba991379Sopenharmony_ci#-*- coding:utf-8 -*-
2ba991379Sopenharmony_ciimport uuid
3ba991379Sopenharmony_ciimport sys
4ba991379Sopenharmony_ciimport subprocess
5ba991379Sopenharmony_ciimport os
6ba991379Sopenharmony_ciimport serial
7ba991379Sopenharmony_ciimport time
8ba991379Sopenharmony_ciimport re
9ba991379Sopenharmony_ci
10ba991379Sopenharmony_cifrom core.base import BaseApp, dec_stepmsg
11ba991379Sopenharmony_cifrom util.file_locker import FileLock
12ba991379Sopenharmony_cifrom util.log_info import logger
13ba991379Sopenharmony_cifrom util.time_info import get_now_time_str_info, get_now_time_info, Timeout, timeout
14ba991379Sopenharmony_cifrom aw.Telnet.TelnetClient import TelConnect
15ba991379Sopenharmony_cifrom aw.Common.Constant import CONSTANT
16ba991379Sopenharmony_cifrom aw.Download.Download import *
17ba991379Sopenharmony_cifrom aw.Common.Common import getHostIp, copyFile, copyDirectory
18ba991379Sopenharmony_cifrom aw.ExtractFile.ExtractFile import *
19ba991379Sopenharmony_cifrom aw.poweronoff.serial_power_on_off import usbPowerOnOff
20ba991379Sopenharmony_cifrom threading import Thread
21ba991379Sopenharmony_ci
22ba991379Sopenharmony_cilock_suffix = CONSTANT.File.LOCK_SUFFIX  #通过文件锁实现并发下载
23ba991379Sopenharmony_cisuc_file = CONSTANT.File.SUC_FILE        #通过本文件是区分版本是否成功下载
24ba991379Sopenharmony_cifailed_file = CONSTANT.File.FAILED_FILE  #通过本文件是标记文件下载失败
25ba991379Sopenharmony_ciREAD_MAXTIMEOUT = 5
26ba991379Sopenharmony_ciREAD_TIMEOUT = 5
27ba991379Sopenharmony_ciREAD_MINITIMEOUT = 2
28ba991379Sopenharmony_ciuboot_finish = 'hisilicon #'
29ba991379Sopenharmony_cicmd_finish = ' #'
30ba991379Sopenharmony_cierror_str_list = ['Unknown', '发送起始帧失败', '发送头帧失败']
31ba991379Sopenharmony_ciip_cmd = 'ping 192.168.18.1'
32ba991379Sopenharmony_ci
33ba991379Sopenharmony_ciclass liteOsUpgrade_linux(BaseApp):
34ba991379Sopenharmony_ci    '''
35ba991379Sopenharmony_ci    @author: cwx1076044
36ba991379Sopenharmony_ci    '''
37ba991379Sopenharmony_ci
38ba991379Sopenharmony_ci    def __init__(self, param_file):
39ba991379Sopenharmony_ci        super().__init__(param_file)
40ba991379Sopenharmony_ci        self.param_List = ["deploy_com",
41ba991379Sopenharmony_ci                        "usb_port",
42ba991379Sopenharmony_ci                           "upgrade_upgradeLocation"]
43ba991379Sopenharmony_ci
44ba991379Sopenharmony_ci    @dec_stepmsg("linux L1 flash")
45ba991379Sopenharmony_ci    def excute(self):
46ba991379Sopenharmony_ci        '''
47ba991379Sopenharmony_ci        #===================================================================================
48ba991379Sopenharmony_ci        #   @Method:        excute(self)
49ba991379Sopenharmony_ci        #   @Precondition:  none
50ba991379Sopenharmony_ci        #   @Func:          升级执行入口
51ba991379Sopenharmony_ci        #   @PostStatus:    none
52ba991379Sopenharmony_ci        #   @eg:            excute()
53ba991379Sopenharmony_ci        #   @return:        True or Flase
54ba991379Sopenharmony_ci        #===================================================================================
55ba991379Sopenharmony_ci        '''
56ba991379Sopenharmony_ci        step_index = self.params_dict.get("step_list").index("liteOsUpgrade_linux_app")
57ba991379Sopenharmony_ci
58ba991379Sopenharmony_ci        # 执行下载
59ba991379Sopenharmony_ci        try:
60ba991379Sopenharmony_ci            if not self.download():
61ba991379Sopenharmony_ci                CONSTANT.ENVERRMESSAGE = "image download fail"
62ba991379Sopenharmony_ci                logger.printLog(CONSTANT.ENVERRMESSAGE)
63ba991379Sopenharmony_ci                return False
64ba991379Sopenharmony_ci        except Exception as e:
65ba991379Sopenharmony_ci            raise e
66ba991379Sopenharmony_ci
67ba991379Sopenharmony_ci
68ba991379Sopenharmony_ci        # 执行升级
69ba991379Sopenharmony_ci        try:
70ba991379Sopenharmony_ci            if not self.upgrade():
71ba991379Sopenharmony_ci                CONSTANT.ENVERRMESSAGE = "board upgrade fail"
72ba991379Sopenharmony_ci                logger.printLog(CONSTANT.ENVERRMESSAGE)
73ba991379Sopenharmony_ci                return False
74ba991379Sopenharmony_ci            return True
75ba991379Sopenharmony_ci        except Exception as e:
76ba991379Sopenharmony_ci            raise e
77ba991379Sopenharmony_ci
78ba991379Sopenharmony_ci    @dec_stepmsg("download")
79ba991379Sopenharmony_ci    @timeout(1800)
80ba991379Sopenharmony_ci    def download(self):
81ba991379Sopenharmony_ci        '''
82ba991379Sopenharmony_ci        #===================================================================================
83ba991379Sopenharmony_ci        #   @Method:        download(self)
84ba991379Sopenharmony_ci        #   @Precondition:  none
85ba991379Sopenharmony_ci        #   @Func:          构建下载到本地的路径,执行相应包的下载
86ba991379Sopenharmony_ci        #   @PostStatus:    none
87ba991379Sopenharmony_ci        #   @eg:            download()
88ba991379Sopenharmony_ci        #   @return:        True or Flase
89ba991379Sopenharmony_ci        #===================================================================================
90ba991379Sopenharmony_ci        '''
91ba991379Sopenharmony_ci        global version_savepath, version_name
92ba991379Sopenharmony_ci        dir_path = CONSTANT.Path.getDirPath()
93ba991379Sopenharmony_ci        if self.params_dict.get("pbiid"):
94ba991379Sopenharmony_ci            version_path = self.params_dict.get("pbiid")
95ba991379Sopenharmony_ci            version_name = str(uuid.uuid5(uuid.NAMESPACE_URL, str(self.params_dict.get("pbiid")) + "FASTBOOT"))
96ba991379Sopenharmony_ci            version_savepath = os.path.join(dir_path, self.params_dict.get("flash_type"), version_name)
97ba991379Sopenharmony_ci        else:
98ba991379Sopenharmony_ci            version_path = self.params_dict.get("upgrade_upgradeLocation")
99ba991379Sopenharmony_ci            version_name = str(uuid.uuid5(uuid.NAMESPACE_URL, (self.params_dict.get("upgrade_upgradeLocation"))))
100ba991379Sopenharmony_ci            version_savepath = os.path.join(dir_path, version_name)
101ba991379Sopenharmony_ci
102ba991379Sopenharmony_ci        if self.params_dict.get("isDownload") == "True":
103ba991379Sopenharmony_ci            logger.printLog("不需要做下载,直接返回")
104ba991379Sopenharmony_ci            return True
105ba991379Sopenharmony_ci
106ba991379Sopenharmony_ci        #执行img下载
107ba991379Sopenharmony_ci        import hashlib
108ba991379Sopenharmony_ci        save_file_str = version_path.replace("/", "").replace("\\", "")
109ba991379Sopenharmony_ci        save_file_name = hashlib.sha1(save_file_str.encode("utf-8")).hexdigest()
110ba991379Sopenharmony_ci        logger.info("download hash value:%s" % (save_file_name))
111ba991379Sopenharmony_ci        save_path_file = os.path.join(dir_path, "record", "%s%s" % (save_file_name, ".txt"))
112ba991379Sopenharmony_ci        if not self.excutedown(version_path, os.path.join(version_savepath, "img"), save_path_file, False):
113ba991379Sopenharmony_ci            logger.error("download img fail")
114ba991379Sopenharmony_ci            return False
115ba991379Sopenharmony_ci
116ba991379Sopenharmony_ci        #保存本地版本路径给devicetest去版本路径下取用例
117ba991379Sopenharmony_ci        saveVersion(save_path_file, os.path.join(version_savepath, "img"))
118ba991379Sopenharmony_ci
119ba991379Sopenharmony_ci        return True
120ba991379Sopenharmony_ci
121ba991379Sopenharmony_ci    def excutedown(self, source_path, download_dir, suc_mark, is_file):
122ba991379Sopenharmony_ci        '''
123ba991379Sopenharmony_ci        #===================================================================================
124ba991379Sopenharmony_ci        #   @Method:        excutedown(source_path, download_dir, is_file)
125ba991379Sopenharmony_ci        #   @Precondition:  none
126ba991379Sopenharmony_ci        #   @Func:          执行下载动作
127ba991379Sopenharmony_ci        #   @PostStatus:    none
128ba991379Sopenharmony_ci        #   @Param:         source_path:资源文件路径
129ba991379Sopenharmony_ci        #                   download_dir:文件下载到本地的文件夹路径
130ba991379Sopenharmony_ci        #                   is_file:是否是文件
131ba991379Sopenharmony_ci        #
132ba991379Sopenharmony_ci        #   @eg:            excutedown("xxxx", "D:\\local\\image", Flase, os_method)
133ba991379Sopenharmony_ci        #   @return:        True or Flase
134ba991379Sopenharmony_ci        #===================================================================================
135ba991379Sopenharmony_ci        '''
136ba991379Sopenharmony_ci        failed_mark = os.path.join(download_dir, failed_file)
137ba991379Sopenharmony_ci        lock_path = os.path.join(download_dir, lock_suffix)
138ba991379Sopenharmony_ci        file_lock = FileLock()
139ba991379Sopenharmony_ci
140ba991379Sopenharmony_ci        if isDownLoadSuccess(download_dir, suc_mark, failed_mark):
141ba991379Sopenharmony_ci            return True
142ba991379Sopenharmony_ci        try:
143ba991379Sopenharmony_ci            nowtime = get_now_time_str_info()
144ba991379Sopenharmony_ci            logger.printLog("%s Downloading, please wait" % nowtime)
145ba991379Sopenharmony_ci            file_lock.lockFile(lock_path)
146ba991379Sopenharmony_ci            ret = ""
147ba991379Sopenharmony_ci            logger.info("Get lock. Start to ")
148ba991379Sopenharmony_ci            if self.params_dict.get("bt_enable") and self.params_dict.get("bt_enable") == "True":
149ba991379Sopenharmony_ci                ret = downloadByBitComet(source_path, download_dir, os_method)
150ba991379Sopenharmony_ci            elif source_path.startswith('\\\\'):
151ba991379Sopenharmony_ci                ret = downloadByCopy(source_path, download_dir, is_file)
152ba991379Sopenharmony_ci            elif self.params_dict.get("pbiid"):
153ba991379Sopenharmony_ci                ret = downlaodByDownloadTool(version_savepath, self.params_dict.get("version_type"), "FASTBOOT", self.params_dict.get("pbiid"))
154ba991379Sopenharmony_ci            elif source_path.startswith("http"):
155ba991379Sopenharmony_ci                ret = downloadFileFromDevCloud(source_path, "", "", download_dir)
156ba991379Sopenharmony_ci
157ba991379Sopenharmony_ci            if source_path.endswith(".zip"):
158ba991379Sopenharmony_ci                zip_name = os.path.basename(source_path)
159ba991379Sopenharmony_ci                ret = extractZipFile(os.path.join(download_dir, zip_name), download_dir)
160ba991379Sopenharmony_ci            if source_path.endswith(".tar.gz") or (source_path.startswith("http") and ("file_id=" in source_path)):
161ba991379Sopenharmony_ci                if source_path.startswith("http") and ("file_id=" in source_path):
162ba991379Sopenharmony_ci                    if source_path.endswith(".tar.gz"):
163ba991379Sopenharmony_ci                        zip_name = source_path.split('=')[-1]
164ba991379Sopenharmony_ci                    else:
165ba991379Sopenharmony_ci                        zip_name = "out.tar.gz"
166ba991379Sopenharmony_ci                else:
167ba991379Sopenharmony_ci                    zip_name = os.path.basename(source_path)
168ba991379Sopenharmony_ci                ret = unTarFile(os.path.join(download_dir, zip_name), download_dir)
169ba991379Sopenharmony_ci            nowtime = get_now_time_str_info()
170ba991379Sopenharmony_ci            logger.printLog("%s download to %s end" % (nowtime, download_dir))
171ba991379Sopenharmony_ci
172ba991379Sopenharmony_ci            if not ret:
173ba991379Sopenharmony_ci                with open(failed_mark, "a+") as fp:
174ba991379Sopenharmony_ci                    fp.write("")
175ba991379Sopenharmony_ci            return ret
176ba991379Sopenharmony_ci        except Exception as e:
177ba991379Sopenharmony_ci            logger.printLog(e)
178ba991379Sopenharmony_ci            raise Exception(e)
179ba991379Sopenharmony_ci        finally:
180ba991379Sopenharmony_ci            file_lock.releaseFile()
181ba991379Sopenharmony_ci
182ba991379Sopenharmony_ci
183ba991379Sopenharmony_ci    @dec_stepmsg("upgrade")
184ba991379Sopenharmony_ci    #@timeout(900)
185ba991379Sopenharmony_ci    def upgrade(self):
186ba991379Sopenharmony_ci        '''
187ba991379Sopenharmony_ci        #===================================================================================
188ba991379Sopenharmony_ci        #   @Method:        upgrade(self)
189ba991379Sopenharmony_ci        #   @Precondition:  none
190ba991379Sopenharmony_ci        #   @Func:          升级相关业务逻辑
191ba991379Sopenharmony_ci        #   @PostStatus:    none
192ba991379Sopenharmony_ci        #   @eg:            upgrade()
193ba991379Sopenharmony_ci        #   @return:        True or Flase
194ba991379Sopenharmony_ci        #===================================================================================
195ba991379Sopenharmony_ci        '''
196ba991379Sopenharmony_ci        logger.printLog('开始升级')
197ba991379Sopenharmony_ci        deploy_com = self.params_dict.get("deploy_com")
198ba991379Sopenharmony_ci        usb_port = self.params_dict.get("usb_port")
199ba991379Sopenharmony_ci        baudrate = self.params_dict.get("baudrate")
200ba991379Sopenharmony_ci        #芯片类型,根据芯片类型获取对应的刷机命令
201ba991379Sopenharmony_ci        flash_type = self.params_dict.get("flash_type")
202ba991379Sopenharmony_ci        burn_usbport = self.params_dict.get("hiburn_usbport")
203ba991379Sopenharmony_ci        device_ip = self.params_dict.get("Device_IP")
204ba991379Sopenharmony_ci        device_netmask = self.params_dict.get("Device_Netmask")
205ba991379Sopenharmony_ci        device_gatewayip = self.params_dict.get("Device_GatewayIP")
206ba991379Sopenharmony_ci        chip_version = self.params_dict.get('chip_version')
207ba991379Sopenharmony_ci        chip_version = chip_version.lower() if chip_version else chip_version
208ba991379Sopenharmony_ci
209ba991379Sopenharmony_ci        if not deploy_com:
210ba991379Sopenharmony_ci            logger.error("deploy_com is NULL !!")
211ba991379Sopenharmony_ci            return False
212ba991379Sopenharmony_ci        if not burn_usbport:
213ba991379Sopenharmony_ci            logger.error("hiburn_usbport is NULL !!")
214ba991379Sopenharmony_ci            return False
215ba991379Sopenharmony_ci        if not baudrate:
216ba991379Sopenharmony_ci            baudrate = 115200
217ba991379Sopenharmony_ci        scriptpath = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))))
218ba991379Sopenharmony_ci        #升级需要的工具归档
219ba991379Sopenharmony_ci        toolworkspace = CONSTANT.OSType.getworkspace()
220ba991379Sopenharmony_ci        hiburntoolpath = os.path.join(toolworkspace, "HiBurnCmdLine", "usb%s_tool" % burn_usbport)
221ba991379Sopenharmony_ci        logger.info("hiburn tool path is: %s" % hiburntoolpath)
222ba991379Sopenharmony_ci        if not os.path.exists(hiburntoolpath):
223ba991379Sopenharmony_ci            if not burn_usbport:
224ba991379Sopenharmony_ci                logger.error("hiburn_usbport is NULL !!")
225ba991379Sopenharmony_ci                return False
226ba991379Sopenharmony_ci            os.makedirs(hiburntoolpath)
227ba991379Sopenharmony_ci            toolpath = os.path.join(scriptpath, "resource", "HiBurnCmdLine.zip")
228ba991379Sopenharmony_ci            logger.info("copy %s to %s" % (toolpath, hiburntoolpath))
229ba991379Sopenharmony_ci            copyFile(toolpath, hiburntoolpath)
230ba991379Sopenharmony_ci            zip_name = os.path.basename(toolpath)
231ba991379Sopenharmony_ci            ret = extractZipFile(os.path.join(hiburntoolpath, zip_name), hiburntoolpath)
232ba991379Sopenharmony_ci            if ret:
233ba991379Sopenharmony_ci                logger.info("unzip to %s succ" % (hiburntoolpath))
234ba991379Sopenharmony_ci                #修改burn.config中的usb口
235ba991379Sopenharmony_ci                configpath = os.path.join(hiburntoolpath, "config", "burn.config")
236ba991379Sopenharmony_ci                all_data = ""
237ba991379Sopenharmony_ci                with open(configpath, "r", encoding="utf-8") as cf:
238ba991379Sopenharmony_ci                    for line in cf:
239ba991379Sopenharmony_ci                        if "usbDeviceNumber=" in line:
240ba991379Sopenharmony_ci                            old_str = line
241ba991379Sopenharmony_ci                            line = line.replace(old_str, "usbDeviceNumber=%s\r\n" % burn_usbport)
242ba991379Sopenharmony_ci                            logger.info("replace line: %s " % line)
243ba991379Sopenharmony_ci                        all_data += line
244ba991379Sopenharmony_ci                with open(configpath, "w", encoding="utf-8") as wf:
245ba991379Sopenharmony_ci                    wf.write(all_data)
246ba991379Sopenharmony_ci            else:
247ba991379Sopenharmony_ci                logger.error("%s is not exit" % hiburntoolpath)
248ba991379Sopenharmony_ci                return False
249ba991379Sopenharmony_ci        #将升级需要的文件拷贝到镜像里面
250ba991379Sopenharmony_ci        local_image_path = os.path.join(version_savepath, "img")
251ba991379Sopenharmony_ci        old_xml_path = os.path.join(scriptpath, "resource", "L1", flash_type, "usb-burn.xml")
252ba991379Sopenharmony_ci        xml_path = os.path.join(local_image_path, "usb-burn.xml")
253ba991379Sopenharmony_ci        copyFile(old_xml_path, xml_path)
254ba991379Sopenharmony_ci        if flash_type.lower() == "ev300":
255ba991379Sopenharmony_ci            chip_type = "Hi3518EV300"
256ba991379Sopenharmony_ci            ubootpath = os.path.join(scriptpath, "resource", "L1", flash_type.lower(), "u-boot-hi3518ev300.bin")
257ba991379Sopenharmony_ci        elif flash_type.lower() == "dv300_linux":
258ba991379Sopenharmony_ci            chip_type = "Hi3516DV300"
259ba991379Sopenharmony_ci            ubootpath = os.path.join(scriptpath, "resource", "L1", flash_type.lower(), "u-boot-hi3516dv300.bin")
260ba991379Sopenharmony_ci        else:
261ba991379Sopenharmony_ci            logger.error("flash_type is : %s " % flash_type)
262ba991379Sopenharmony_ci            return False
263ba991379Sopenharmony_ci        copyFile(ubootpath, local_image_path)
264ba991379Sopenharmony_ci        scriptfile = os.path.join(scriptpath, "resource", "L1", f'{flash_type.lower()}', "update.txt")
265ba991379Sopenharmony_ci        logger.info(f'scriptfile:{scriptfile}')
266ba991379Sopenharmony_ci
267ba991379Sopenharmony_ci        current_path = os.getcwd()
268ba991379Sopenharmony_ci        logger.info("before excute hiburn,current path is: %s" % current_path)
269ba991379Sopenharmony_ci        os.chdir(hiburntoolpath)
270ba991379Sopenharmony_ci        logger.info("excute hiburn path is: %s" % os.getcwd())
271ba991379Sopenharmony_ci        #擦除fastboot
272ba991379Sopenharmony_ci        logger.printLog('erase fastboot')
273ba991379Sopenharmony_ci        flash_uboot_xml = os.path.join(scriptpath, "resource", "L1", flash_type.lower(), "flash_fastboot.xml")
274ba991379Sopenharmony_ci        cmd = ".\jre\\bin\java -jar hiburn.jar --erase -n %s -m serial %s -x %s" % (chip_type, deploy_com.upper(), flash_uboot_xml)
275ba991379Sopenharmony_ci        self.eraseDevice(cmd, usb_port)
276ba991379Sopenharmony_ci
277ba991379Sopenharmony_ci        retry = 0
278ba991379Sopenharmony_ci        while retry < 3:
279ba991379Sopenharmony_ci            #usb刷机
280ba991379Sopenharmony_ci            cmd = ".\jre\\bin\java -jar hiburn.jar --burn -n %s -m USBBootrom -x %s" % (chip_type, xml_path)
281ba991379Sopenharmony_ci            logger.info("cmd is: %s" % cmd)
282ba991379Sopenharmony_ci            ret, outpri = subprocess.getstatusoutput(cmd)
283ba991379Sopenharmony_ci            logger.info("usb upgrade result: %s " % ret)
284ba991379Sopenharmony_ci            logger.info("print console: %s " % outpri)
285ba991379Sopenharmony_ci            if ret != 0:
286ba991379Sopenharmony_ci                if ret == 4 and retry < 2:
287ba991379Sopenharmony_ci                    time.sleep(10)
288ba991379Sopenharmony_ci                    retry = retry + 1
289ba991379Sopenharmony_ci                    logger.info('flash fail,so flash once again')
290ba991379Sopenharmony_ci                    continue
291ba991379Sopenharmony_ci                logger.info(ret)
292ba991379Sopenharmony_ci                logger.error("hiburn usb upgrade failed!!")
293ba991379Sopenharmony_ci                return False
294ba991379Sopenharmony_ci            retry = retry + 3
295ba991379Sopenharmony_ci        os.chdir(current_path)
296ba991379Sopenharmony_ci        logger.info("hiburn upgrade end, check board status")
297ba991379Sopenharmony_ci        time.sleep(10)
298ba991379Sopenharmony_ci        try:
299ba991379Sopenharmony_ci            logger.info("打开serial")
300ba991379Sopenharmony_ci            ser = serial.Serial(deploy_com, int(baudrate), timeout=0)
301ba991379Sopenharmony_ci            if self.bootUpUboot(ser,scriptfile) and self.configureIp(ser, flash_type, device_ip, device_netmask, device_gatewayip) and self.checkStatus(ser):
302ba991379Sopenharmony_ci                return True
303ba991379Sopenharmony_ci            return False
304ba991379Sopenharmony_ci        except Exception as e:
305ba991379Sopenharmony_ci            logger.info(e)
306ba991379Sopenharmony_ci            return False
307ba991379Sopenharmony_ci        finally:
308ba991379Sopenharmony_ci            ser.close()
309ba991379Sopenharmony_ci            logger.info("close serial")
310ba991379Sopenharmony_ci
311ba991379Sopenharmony_ci    def bootUpUboot(self,ser,scriptfile):
312ba991379Sopenharmony_ci        '''
313ba991379Sopenharmony_ci        启动uboot
314ba991379Sopenharmony_ci        '''
315ba991379Sopenharmony_ci        reset_count = 0
316ba991379Sopenharmony_ci        while reset_count < 2:
317ba991379Sopenharmony_ci            if ser.is_open == False:
318ba991379Sopenharmony_ci                ser.open()
319ba991379Sopenharmony_ci            logger.info("get device status")
320ba991379Sopenharmony_ci            board_type = getBoardType(ser)
321ba991379Sopenharmony_ci            if board_type == "uboot":
322ba991379Sopenharmony_ci                with open(scriptfile, "r") as fp:
323ba991379Sopenharmony_ci                    lines = fp.readlines()
324ba991379Sopenharmony_ci                for line in lines:
325ba991379Sopenharmony_ci                    if not line:
326ba991379Sopenharmony_ci                        logger.info("cmd is: %s " % line)
327ba991379Sopenharmony_ci                        continue
328ba991379Sopenharmony_ci                    if "reset" in line:
329ba991379Sopenharmony_ci                        ret = sendCmd(ser, line, READ_MAXTIMEOUT)
330ba991379Sopenharmony_ci                        continue
331ba991379Sopenharmony_ci                    ret = sendCmd(ser, line, READ_MINITIMEOUT)
332ba991379Sopenharmony_ci                board_type = getBoardType(ser)
333ba991379Sopenharmony_ci                if board_type != "OHOS":
334ba991379Sopenharmony_ci                    if  reset_count < 2:
335ba991379Sopenharmony_ci                        logger.info('after reset;the device status is error,reset device again,reset_count:%d' % reset_count)
336ba991379Sopenharmony_ci                        reset_count += 1
337ba991379Sopenharmony_ci                        time.sleep(20)
338ba991379Sopenharmony_ci                        continue
339ba991379Sopenharmony_ci                    logger.error("upgrade fail")
340ba991379Sopenharmony_ci                    return False
341ba991379Sopenharmony_ci                return True
342ba991379Sopenharmony_ci            else:
343ba991379Sopenharmony_ci                logger.info('before reset;the device status is error,reset device again,reset_count:%d'%reset_count)
344ba991379Sopenharmony_ci                reset_count += 1
345ba991379Sopenharmony_ci                time.sleep(20)
346ba991379Sopenharmony_ci                continue
347ba991379Sopenharmony_ci        else:
348ba991379Sopenharmony_ci            return False
349ba991379Sopenharmony_ci
350ba991379Sopenharmony_ci    def configureIp(self,ser,flash_type, device_ip, device_netmask, device_gatewayip):
351ba991379Sopenharmony_ci        '''
352ba991379Sopenharmony_ci        配置ip,确认配置情况
353ba991379Sopenharmony_ci        '''
354ba991379Sopenharmony_ci        rerty_count = 0
355ba991379Sopenharmony_ci        # test_count = 0
356ba991379Sopenharmony_ci        while rerty_count <= 2:
357ba991379Sopenharmony_ci            if flash_type.lower() == "dv300_linux":
358ba991379Sopenharmony_ci                if not self.afterRebootDvConfigure(ser, device_ip, device_netmask, device_gatewayip):
359ba991379Sopenharmony_ci                    return False
360ba991379Sopenharmony_ci            elif flash_type.lower() == "ev300":
361ba991379Sopenharmony_ci                if not self.afterRebootEvConfigure(ser):
362ba991379Sopenharmony_ci                    return False
363ba991379Sopenharmony_ci            time.sleep(5)
364ba991379Sopenharmony_ci
365ba991379Sopenharmony_ci            ret = sendCmd(ser, ip_cmd, READ_MINITIMEOUT)
366ba991379Sopenharmony_ci            logger.info(ret)
367ba991379Sopenharmony_ci            # if test_count ==0 :
368ba991379Sopenharmony_ci            #     logger.printLog('ip 配置失败')
369ba991379Sopenharmony_ci            #     test_count = 1
370ba991379Sopenharmony_ci            #     continue
371ba991379Sopenharmony_ci            if 'Reply from 192.168.18.1' in ret:
372ba991379Sopenharmony_ci                logger.info('ip 配置成功')
373ba991379Sopenharmony_ci                return True
374ba991379Sopenharmony_ci            elif 'Ping: sending ICMP echo request failed' in ret:
375ba991379Sopenharmony_ci                logger.printLog('ip 配置失败')
376ba991379Sopenharmony_ci                logger.info('重新配置ip')
377ba991379Sopenharmony_ci                rerty_count += 1
378ba991379Sopenharmony_ci            else:
379ba991379Sopenharmony_ci                return True
380ba991379Sopenharmony_ci
381ba991379Sopenharmony_ci    def afterRebootDvConfigure(self,ser, device_ip, device_netmask, device_gatewayip):
382ba991379Sopenharmony_ci        logger.info("dv300_linux configure ip")
383ba991379Sopenharmony_ci        init_cmd = "ifconfig eth0 %s netmask %s gateway %s \r" % (device_ip, device_netmask, device_gatewayip)
384ba991379Sopenharmony_ci        sendCmd(ser, init_cmd, READ_MINITIMEOUT)
385ba991379Sopenharmony_ci        sendCmd(ser, 'ifconfig\r', READ_MINITIMEOUT)
386ba991379Sopenharmony_ci        return True
387ba991379Sopenharmony_ci
388ba991379Sopenharmony_ci    def afterRebootEvConfigure(self,ser):
389ba991379Sopenharmony_ci        logger.info("ev300 configuring ,setup wifi")
390ba991379Sopenharmony_ci        cmd = 'ls\r'
391ba991379Sopenharmony_ci        ret = sendCmd(ser, cmd, READ_MINITIMEOUT)
392ba991379Sopenharmony_ci        if not "sdcard" in ret.lower():
393ba991379Sopenharmony_ci            cmd = 'mkdir /sdcard\r'
394ba991379Sopenharmony_ci            ret = sendCmd(ser, cmd, READ_MINITIMEOUT)
395ba991379Sopenharmony_ci            if "error:" in ret.lower():
396ba991379Sopenharmony_ci                logger.error("mkdir /sdcard fail")
397ba991379Sopenharmony_ci                return False
398ba991379Sopenharmony_ci        cmd = 'mount /dev/mmcblk0p0 /sdcard vfat\r'
399ba991379Sopenharmony_ci        ret = sendCmd(ser, cmd, READ_MINITIMEOUT)
400ba991379Sopenharmony_ci        cmd = 'ls /sdcard\r'
401ba991379Sopenharmony_ci        ret = sendCmd(ser, cmd, READ_MINITIMEOUT)
402ba991379Sopenharmony_ci        cmd = 'cd /sdcard/wpa\r'
403ba991379Sopenharmony_ci        ret = sendCmd(ser, cmd, READ_MINITIMEOUT)
404ba991379Sopenharmony_ci        cmd = 'exec wpa_supplicant -i wlan0 -c wpa_supplicant.conf \r'
405ba991379Sopenharmony_ci        ret = sendCmd(ser, cmd, READ_MAXTIMEOUT)
406ba991379Sopenharmony_ci        if "error:" in ret.lower():
407ba991379Sopenharmony_ci            logger.error("setup wifi fail")
408ba991379Sopenharmony_ci            return False
409ba991379Sopenharmony_ci        cmd = 'ifconfig\r'
410ba991379Sopenharmony_ci        ret = sendCmd(ser, cmd, READ_MINITIMEOUT)
411ba991379Sopenharmony_ci        if "error:" in ret.lower():
412ba991379Sopenharmony_ci            logger.error("ifconfig fail")
413ba991379Sopenharmony_ci            return False
414ba991379Sopenharmony_ci        return True
415ba991379Sopenharmony_ci
416ba991379Sopenharmony_ci    def eraseDevice(self, cmd, usb_port):
417ba991379Sopenharmony_ci        '''
418ba991379Sopenharmony_ci        ret 暂时没有作用,先使用out
419ba991379Sopenharmony_ci        '''
420ba991379Sopenharmony_ci        erase_retry = 0
421ba991379Sopenharmony_ci        while erase_retry < 3:
422ba991379Sopenharmony_ci            # 通电
423ba991379Sopenharmony_ci            PowerOnByThread(usb_port)
424ba991379Sopenharmony_ci            logger.info("cmd is: %s" % cmd)
425ba991379Sopenharmony_ci            ret, outpri = subprocess.getstatusoutput(cmd)
426ba991379Sopenharmony_ci            logger.info("flash fastboot result: %s " % ret)
427ba991379Sopenharmony_ci            logger.info("print console: %s " % outpri)
428ba991379Sopenharmony_ci            is_earse_again = any([True if item in outpri else False for item in error_str_list])
429ba991379Sopenharmony_ci            if ret == 0 and erase_retry < 2 and not is_earse_again :
430ba991379Sopenharmony_ci                logger.info('檫除成功'.center(20,'*'))
431ba991379Sopenharmony_ci                break
432ba991379Sopenharmony_ci            elif is_earse_again:
433ba991379Sopenharmony_ci                logger.info('檫除存在问题 重新上下电 重新檫除')
434ba991379Sopenharmony_ci                erase_retry += 1
435ba991379Sopenharmony_ci                time.sleep(5)
436ba991379Sopenharmony_ci                continue
437ba991379Sopenharmony_ci            else:
438ba991379Sopenharmony_ci                logger.info('other error')
439ba991379Sopenharmony_ci                return False
440ba991379Sopenharmony_ci        else:
441ba991379Sopenharmony_ci            return False
442ba991379Sopenharmony_ci
443ba991379Sopenharmony_ci    def checkStatus(self, ser):
444ba991379Sopenharmony_ci        times = 0
445ba991379Sopenharmony_ci        while times < 3:
446ba991379Sopenharmony_ci            ret1 = sendCmd(ser, 'ps -elf', READ_TIMEOUT)
447ba991379Sopenharmony_ci            list_ret = re.findall('appspawn', ret1)
448ba991379Sopenharmony_ci            logger.info(list_ret)
449ba991379Sopenharmony_ci            number = list_ret.count('appspawn')
450ba991379Sopenharmony_ci            logger.info(number)
451ba991379Sopenharmony_ci            if number >= 2:
452ba991379Sopenharmony_ci                return True
453ba991379Sopenharmony_ci            else:
454ba991379Sopenharmony_ci                times += 1
455ba991379Sopenharmony_ci                time.sleep(3)
456ba991379Sopenharmony_ci        logger.info("No two appspawn processes, please check the device!")
457ba991379Sopenharmony_ci        return False
458ba991379Sopenharmony_ci
459ba991379Sopenharmony_cidef PowerOnByThread(usb_port,wait_time=10):
460ba991379Sopenharmony_ci    thread = Thread(target=boardPowerOn, args=[usb_port, wait_time])
461ba991379Sopenharmony_ci    thread.start()
462ba991379Sopenharmony_ci    logger.info("thread board power on start")
463ba991379Sopenharmony_ci
464ba991379Sopenharmony_ci
465ba991379Sopenharmony_cidef boardPowerOn(usb_port, waittime):
466ba991379Sopenharmony_ci    logger.info("board power on start")
467ba991379Sopenharmony_ci    time.sleep(waittime)
468ba991379Sopenharmony_ci
469ba991379Sopenharmony_ci    #对端口下电
470ba991379Sopenharmony_ci    if not usbPowerOnOff('127.0.0.1', '7788', usb_port, "off"):
471ba991379Sopenharmony_ci        logger.error("board power off failed")
472ba991379Sopenharmony_ci        return False
473ba991379Sopenharmony_ci
474ba991379Sopenharmony_ci    #对端口上电
475ba991379Sopenharmony_ci    if not usbPowerOnOff('127.0.0.1', '7788', usb_port, "on"):
476ba991379Sopenharmony_ci        logger.error("board power on failed")
477ba991379Sopenharmony_ci        return False
478ba991379Sopenharmony_ci    logger.info("board power on end")
479ba991379Sopenharmony_ci
480ba991379Sopenharmony_ci
481ba991379Sopenharmony_cidef getBoardType(ser):
482ba991379Sopenharmony_ci    ret = sendCmd(ser, '\r', READ_TIMEOUT)
483ba991379Sopenharmony_ci    # if 'HMOS' in ret or 'OHOS' in ret or '#' in ret:
484ba991379Sopenharmony_ci    #     ostype = 'OHOS'
485ba991379Sopenharmony_ci    # elif 'hisilicon' in ret:
486ba991379Sopenharmony_ci    #     ostype = 'uboot'
487ba991379Sopenharmony_ci    if 'hisilicon' in ret:
488ba991379Sopenharmony_ci        ostype = 'uboot'
489ba991379Sopenharmony_ci    elif 'HMOS' in ret or 'OHOS' in ret or '#' in ret:
490ba991379Sopenharmony_ci        ostype = 'OHOS'
491ba991379Sopenharmony_ci    elif ' #' in ret:
492ba991379Sopenharmony_ci        ostype = 'linux'
493ba991379Sopenharmony_ci    else:
494ba991379Sopenharmony_ci        ostype = 'bootrom'
495ba991379Sopenharmony_ci    logger.info("board type is: %s" % ostype)
496ba991379Sopenharmony_ci    return ostype
497ba991379Sopenharmony_ci
498ba991379Sopenharmony_cidef sendCmd(ser, cmd, timeout):
499ba991379Sopenharmony_ci    logger.info("cmd is: %s " % cmd)
500ba991379Sopenharmony_ci    ser.write((cmd + '\n').encode())
501ba991379Sopenharmony_ci    time.sleep(5)
502ba991379Sopenharmony_ci    ret = ''
503ba991379Sopenharmony_ci    i = 0
504ba991379Sopenharmony_ci    while True:
505ba991379Sopenharmony_ci        out = ser.read(ser.inWaiting())
506ba991379Sopenharmony_ci        if not out:
507ba991379Sopenharmony_ci            break
508ba991379Sopenharmony_ci        if i > 12:
509ba991379Sopenharmony_ci            break
510ba991379Sopenharmony_ci        ret = ret + out.decode(encoding="utf-8", errors="ignore")
511ba991379Sopenharmony_ci        time.sleep(timeout)
512ba991379Sopenharmony_ci        i = i + 1
513ba991379Sopenharmony_ci    logger.info("result is: %s " % ret)
514ba991379Sopenharmony_ci    return ret
515ba991379Sopenharmony_ci
516ba991379Sopenharmony_ci
517ba991379Sopenharmony_ci
518ba991379Sopenharmony_ciif __name__ == "__main__":
519ba991379Sopenharmony_ci    param_file = sys.argv[1]
520ba991379Sopenharmony_ci    if not param_file:
521ba991379Sopenharmony_ci        logger.printLog("Missing params file")
522ba991379Sopenharmony_ci        sys.exit(-1)
523ba991379Sopenharmony_ci    try:
524ba991379Sopenharmony_ci        uphandle = liteOsUpgrade_linux(param_file)
525ba991379Sopenharmony_ci        uphandle._excuteApp()
526ba991379Sopenharmony_ci    except Exception as e:
527ba991379Sopenharmony_ci        logger.printLog(e)
528ba991379Sopenharmony_ci        sys.exit(-1)
529ba991379Sopenharmony_ci
530