• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2# coding=utf-8
3
4'''
5* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED.
6* Licensed under the Apache License, Version 2.0 (the "License");
7* you may not use this file except in compliance with the License.
8* You may obtain a copy of the License at
9*
10*     http://www.apache.org/licenses/LICENSE-2.0
11*
12* Unless required by applicable law or agreed to in writing, software
13* distributed under the License is distributed on an "AS IS" BASIS,
14* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15* See the License for the specific language governing permissions and
16* limitations under the License.
17*
18* Description: nv build scripts.
19'''
20
21import os
22import sys
23import re
24import subprocess
25import configparser
26import shutil
27import sys
28import xml.etree.ElementTree as ET
29import copy
30from ctypes import *
31import time
32import hashlib
33import binascii
34import datetime
35from zlib import crc32
36import struct
37sys.path.append("'..', '..', 'build'")
38#from  scripts.analyze_dependence  import user_pannel_config
39
40#-----------------------------------基本错误定义-----------------------------------
41HI_ERR_SUCCESS = 0
42#-----------------------------------基本类型定义-----------------------------------
43HI_CHAR = c_char
44HI_S8 = c_byte
45HI_U8 = c_ubyte
46HI_S16 = c_short
47HI_U16 = c_ushort
48HI_S32 = c_int
49HI_U32 = c_uint
50#-----------------------------------NV结构体定义-----------------------------------
51class NV_FILE_STRU(Structure):
52    _fields_ = [
53        ("magic", HI_U32),
54        ("crc", HI_U32),
55        ("ver", HI_U8),
56        ("head_len", HI_U8),
57        ("total_num", HI_U16),
58        ("seq", HI_U32),
59        ("ver_magic", HI_U32),
60        ("flash_size", HI_U32),
61        ("keep_id_range", HI_U8*2),
62        ("reserve", HI_U8*2),
63        ("nv_item_index", HI_U8*0),
64        ]
65
66class NV_ITEM_INDEX_STRU(Structure):
67    _fields_ = [
68        ("nv_id", HI_U8),
69        ("nv_len", HI_U8),
70        ("nv_offset", HI_U16),
71        ]
72NV_ITEM_INDEX_LEN = 4
73NV_ITEM_CRC_LEN = 4
74
75HNV_MAGIC = 0x24564E48
76FNV_MAGIC = 0x23564E46
77
78#SEC_CONN_SALT = '"sec conn salt"'
79#SEC_NV_ID = 0x8c
80
81###############################NV 分区头格式 ###############################################
82#Hi3921不再在NV中体现Factory/Modem/APP等不同分区头
83
84###############################NV项头信息###############################################
85#Hi3921各个NV项(条目)没有头信息.
86
87#-----------------------------------生成HNV文件流程-----------------------------------
88def nv_process_mk_section(element_root, src_bin_dic, is_factory):
89    nv_id_list = []
90    nv_keep_id_list = []
91    nv_item_bin_list = []
92    nv_item_index_bin_list = []
93    nv_total_size = 0
94    nv_offset = 0
95    nv_len = 0
96    nv_total_num = 0
97
98    #1.遍历,取出工厂区或非工厂区的所有NV ID,并排序
99    for element_grp in element_root:
100#        print("element_grp: ", element_grp)
101#        print("NAME: ", element_grp.attrib['NAME'])
102        if True == is_factory:
103            if element_grp.attrib['NAME'] == 'Factory':
104                for nv_element in element_grp:
105                    nv_id_list.append(int(nv_element.attrib['ID'], 16))
106                break;
107        else:
108            if element_grp.attrib['NAME'] != 'Factory':
109                for nv_element in element_grp:
110                    nv_id_list.append(int(nv_element.attrib['ID'], 16))
111                    if element_grp.attrib['NAME'] == 'Keep':
112                        nv_keep_id_list.append(int(nv_element.attrib['ID'], 16))
113
114    nv_id_list.sort()
115    nv_keep_id_list.sort()
116    nv_total_num = len(nv_id_list)
117    nv_offset = sizeof(NV_FILE_STRU)+nv_total_num*4#NV相对本区的偏移初始化在索引区之后
118
119    #print(nv_id_list)
120
121    #2.按照ID顺序生成nv_item_bin(含nv_item头和nv_item内容),添加到nv_item_bin_list中
122    for nv_id in nv_id_list:
123        #申请nv_item_bin空间并转换成nv_item_st
124        src_bin = src_bin_dic[hex(nv_id)]
125        nv_len = len(src_bin)
126        nv_item_bin = bytearray(nv_len+NV_ITEM_CRC_LEN)#申请空间
127
128        #填充nv_item_bin,并将nv_item_bin添加到nv_item_bin_list中
129        nv_item_bin[0:] = src_bin#拷贝bin
130        nv_item_bin[nv_len:] = struct.pack('<L', crc32(src_bin))
131        nv_item_bin_list.append(nv_item_bin)
132
133        #累加nv_item_bin总大小
134        nv_total_size = nv_total_size+nv_len+NV_ITEM_CRC_LEN#计算所有nv长度
135
136        #NV索引
137        nv_item_index_bin = bytearray(NV_ITEM_INDEX_LEN)
138        nv_item_index_st = NV_ITEM_INDEX_STRU.from_buffer(nv_item_index_bin)
139        nv_item_index_st.nv_id = nv_id
140        nv_item_index_st.nv_len = nv_len
141        nv_item_index_st.nv_offset = nv_offset
142        nv_item_index_bin_list.append(nv_item_index_bin)
143        nv_offset = nv_offset+nv_len+NV_ITEM_CRC_LEN
144
145    #3.生成section_bin
146    #申请section_bin空间
147    section_bin = bytearray(nv_total_size)
148
149    #将nv_item_bin依次拷贝到section_bin的后面
150    offset = 0
151    for nv_item_bin in nv_item_bin_list:
152        section_bin[offset:] = nv_item_bin
153        offset = offset+len(nv_item_bin)
154
155    #4.生成index_bin
156    index_bin = bytearray(NV_ITEM_INDEX_LEN*nv_total_num)
157    offset = 0
158    for nv_item_index_bin in nv_item_index_bin_list:
159        index_bin[offset:] = nv_item_index_bin
160        offset = offset+NV_ITEM_INDEX_LEN
161
162    return (HI_ERR_SUCCESS, nv_total_num, section_bin, index_bin, nv_keep_id_list)
163
164'''
165功能:生成hnv文件
166入参
167element_root:nv根节点
168src_bin_dic:nv bin字典  {'0xf01':bytearray(...),....}
169is_factory:是否是工厂区NV文件
170返回值
171ret错误码
172nv_file_Bin: 类型bytearray   nv文件内容
173'''
174def hi_nv_process_mk_hnv(element_root, src_bin_dic, nv_file_name, is_factory):
175    #print(src_bin_dic)
176    global g_nv_env
177
178    #2.生成index_bin和section_bin
179#    print("element_root: ", element_root)
180    (ret, nv_total_num, section_bin, index_bin, nv_keep_id_list) = nv_process_mk_section(element_root, src_bin_dic, is_factory)
181    if ret != HI_ERR_SUCCESS:
182        return(ret, None)
183
184    nv_name = ''
185    if is_factory == True:
186        nv_name = 'Factory NV'
187    else:
188        nv_name = 'Normal NV'
189
190    print("%s total num:%d"%(nv_name,nv_total_num))
191
192    nv_index_total_size = len(index_bin)
193    nv_bin_total_size = len(section_bin)
194
195    #3.申请nv_file_Bin空间,转成nv_file_st结构并填充nv_file_st
196    nv_file_Bin = bytearray(g_nv_env.flash_size)
197
198    nv_file_st = NV_FILE_STRU.from_buffer(nv_file_Bin)
199
200    #填充nv_file_st
201    if is_factory == True:
202        nv_file_st.magic = FNV_MAGIC
203    else:
204        nv_file_st.magic = HNV_MAGIC
205    nv_file_st.ver = 0
206    nv_file_st.head_len = sizeof(NV_FILE_STRU)#TODO:头的定长部分暂时没有四字节对齐
207    print('NV_FILE_STRU :'+str(nv_file_st.head_len))
208    nv_file_st.total_num = nv_total_num
209    nv_file_st.seq = 0
210    nv_file_st.ver_magic = g_nv_env.ver_magic
211    nv_file_st.flash_size = g_nv_env.flash_size
212    nv_file_st.reserve[0] = 0
213    nv_file_st.reserve[1] = 0
214    if(len(nv_keep_id_list) == 0):
215        nv_file_st.keep_id_range[0] = 0
216        nv_file_st.keep_id_range[1] = 0
217    else:
218        nv_file_st.keep_id_range[0] = 0x80
219        nv_file_st.keep_id_range[1] = 0x9f
220
221    #将index_bin添加到管理区后面,作为管理区的索引
222    offset = sizeof(NV_FILE_STRU)
223    nv_file_Bin[offset:offset+nv_index_total_size] = index_bin
224    offset = offset+nv_index_total_size
225
226    #将section_bin添加到管理区的索引后面
227    nv_file_Bin[offset:offset+nv_bin_total_size] = section_bin
228    offset = offset+nv_bin_total_size
229
230    print("%s total size:%d"%(nv_name, offset))
231    if offset > g_nv_env.flash_size:
232        print("Error: NV is larger than flash_size:%d"%(g_nv_env.flash_size))
233        exit(-1)
234
235    #将nv_flash空闲区域置为F
236    for i in range(offset, g_nv_env.flash_size):
237        nv_file_Bin[i] = 0xFF
238
239    #计算整区的crc32
240    nv_file_st.crc = crc32(nv_file_Bin[8:g_nv_env.flash_size])
241
242    return (HI_ERR_SUCCESS, nv_file_Bin)
243
244class NvEnv:
245    def __init__(self):
246        self.app_name = []#app名称
247        self.root_dir = []#编译根目录
248        self.mdm_xml = []#mdm_xml全路径
249        self.app_xml = []#app_xml全路径
250        self.app_sdk_level = []#app sdk等级
251        self.app_cfg_dir = []#客制化文件夹路径,带产品形态路径
252        self.src_bin_dir = []#原bin路径,带产品形态路径
253
254        self.product_type = []#产品形态名称
255        self.temp_dir = []#临时文件夹路径,带产品形态
256        self.combin_xml = []#合并后xml全路径,带or不带产品形态
257        self.nv_tool_dir = []#
258        self.nv_h_dir = []#
259        self.nv_bin_max_size = 0
260        self.flash_size = 0
261        self.ver_magic = 0
262
263g_nv_env = NvEnv()
264
265def hi_str_to_int(line, num):
266    if num is not None:
267        return int(line, num)
268    match1 = re.match(r'\s*0x', line)
269    match2 = re.match(r'\s*0X', line)
270    if match1 or match2:
271        return int(line, 16)
272    else:
273        return int(line, 10)
274
275''' '''
276def hi_nv_set_cfg(root_dir, product_lib_out, xml_hfile_dir, product_name, app_name, hnv_dir, flash_size, ver_magic, hnv_file_name):
277    global g_nv_env
278    subver = g_subver_name
279    if subver =='common':
280        subver = app_name
281
282    if hnv_dir is None:#hnv存放位置
283        g_nv_env.hnv_dir=product_lib_out
284    else:
285        g_nv_env.hnv_dir=hnv_dir
286
287    g_nv_env.nv_h_dir=xml_hfile_dir#存放结构体txt文件存放位置
288    g_nv_env.app_name=app_name#app名称
289    g_nv_env.product_type=product_name#产品形态名称
290    g_nv_env.root_dir=root_dir#根目录
291    g_nv_env.temp_dir=os.path.join(product_lib_out, app_name, '%s%s'%(g_common_ver, g_subver_name))#临时文件目录
292    print('root_dir:', root_dir)
293    g_nv_env.mdm_xml=os.path.join(root_dir, 'xml_file', hnv_file_name)
294    print('mdm_xml:', g_nv_env.mdm_xml)
295    g_nv_env.app_xml=os.path.join(root_dir, 'xml_file', 'app_nvi_db.xml')
296    g_nv_env.app_cfg_dir=os.path.join(root_dir, 'xml_file')#区分不同产品形态
297    print('HNV NAME:' + hnv_file_name)
298    g_nv_env.combin_xml=os.path.join(product_lib_out, app_name, hnv_file_name)#合并后combin.xml路径
299    g_nv_env.combin_product_xml=os.path.join(g_nv_env.temp_dir, 'mss_nvi_db_%s.xml'%(g_nv_env.product_type))#合并分割后combin_coo.xml路径
300    g_nv_env.combin_product_security_xml=os.path.join(g_nv_env.temp_dir, 'combin_%s_security.xml'%(g_nv_env.product_type))#合并分割后combin_coo.xml路径
301
302    g_nv_env.src_bin_dir=os.path.join(root_dir, 'app', g_nv_env.app_name, 'nv', 'src_bin', g_nv_env.product_type)#存放必源src bin文件路径
303    g_nv_env.nv_tool=os.path.join(root_dir, 'tools', 'nv', 'cdbm')#nv工具路径
304    print('nv_tool:', g_nv_env.nv_tool)
305    #g_nv_env.pwd_nv_tool=os.path.join(root_dir, 'tools', 'nv', 'pwd_nv_tool.exe')#pwd nv 制作工具路径
306    g_nv_env.nv_bin_max_size=65536#暂定最大支持64K flash
307
308    g_nv_env.flash_size=flash_size
309    g_nv_env.ver_magic=ver_magic
310    return 0
311
312def hi_nv_fomat_nv_id(root):
313    ret = 0
314    for grp in root:
315        for nv in grp:
316            if 'ID' in nv.attrib.keys():
317                str_id=nv.attrib['ID']
318                int_id=hi_str_to_int(str_id, None)
319                str_id=hex(int_id)
320                nv.attrib['ID']=str_id
321    return 0
322
323"""
324合并xml;nv id标准化;nv 按组号进行排序
325"""
326def HI_NV_XmlCombineXml(src_xml_list, combin_xml):
327    root_list=[]
328    group_dics={}
329    exist_item_id_list=[]
330    global g_nv_env
331
332    for src_xml in src_xml_list:
333        tree = ET.parse(src_xml)
334        root = tree.getroot()
335        hi_nv_fomat_nv_id(root)#标准化NVID
336        root_list.append(root)
337
338    new_root=ET.Element('HISTUDIO')
339    print('root_list', root_list)
340
341    #判断是否有重复的ID
342    for root in root_list:
343        grp_list=root.findall('GROUP')#找到所有的grp
344        for grp in grp_list:
345            item_list=grp.findall('NV')
346            for item in item_list:
347                str_id=item.attrib['ID']
348                int_id=hi_str_to_int(str_id, None)
349                if int_id in exist_item_id_list:
350                    print(exist_item_id_list)
351                    return -1
352                exist_item_id_list.append(int_id)
353
354    #合并xml
355    for root in root_list:
356        grp_list=root.findall('GROUP')#找到所有的grp
357        for grp in grp_list:
358            grp_name=grp.attrib['NAME']
359            if not grp_name in group_dics.keys():
360                new_root.append(grp)
361                group_dics[grp_name]=grp
362            else:
363                old_grp=group_dics[grp_name]
364                sub_elements=grp.findall('NV')
365                old_grp.extend(sub_elements)
366
367    #对新xml进行排序
368    element_grp_list=[]
369    for element_grp in new_root:
370        element_grp_list.append(element_grp)
371
372    element_grp_list.sort(key=lambda x:int(x.attrib['ID'], 16))
373    i=0
374    while i< len(element_grp_list):
375        new_root[i]=element_grp_list[i]
376        i=i+1
377
378    #回写xml
379    new_tree=ET.ElementTree(new_root)
380    new_tree.write(combin_xml, encoding="utf-8")
381
382def hi_nv_mk_temp_dir(temp_dir, hnv_dir):
383    global g_nv_env
384    if os.path.exists(temp_dir):
385        shutil.rmtree(temp_dir)
386        os.makedirs(temp_dir)
387    else:
388        os.makedirs(temp_dir)
389
390    if hnv_dir is None:
391        pass
392    elif not os.path.exists(hnv_dir):
393        os.makedirs(hnv_dir)
394    else:
395        pass
396
397"""
398合并mss和app xml
399"""
400def hi_nv_combine_mss_and_app_xml():
401    global g_nv_env
402    src_xml_list=[]
403    src_xml_list.append(g_nv_env.mdm_xml)
404    print('mdmxml:'+g_nv_env.mdm_xml)
405    if os.path.exists(g_nv_env.app_xml):
406        src_xml_list.append(g_nv_env.app_xml)
407        print('appxml:'+g_nv_env.app_xml)
408    print('src_xml_list:', src_xml_list)
409    print('combin_xml:%s'%g_nv_env.combin_xml)
410    HI_NV_XmlCombineXml(src_xml_list, g_nv_env.combin_xml)
411
412def HI_NV_XmlSplitByProductType(src_xml, product_list, dst_xml_list):
413    new_root_list=[]
414    tree = ET.parse(src_xml)
415    root = tree.getroot()
416    i=0
417    #print('src_xml', src_xml)
418    #print('product_list', product_list)
419    #print('dst_xml_list', dst_xml_list)
420    while i<len(product_list):
421        new_root=copy.deepcopy(root)
422        for grp in new_root:
423            del_nv_list=[]
424            for nv in grp:
425                list=nv.attrib['DEV'].lower().split('-')
426                #print('list', list)
427                if product_list[i] not in list:
428                    del_nv_list.append(nv)
429                else:
430                    pass
431                    #del nv.attrib['DEV']#删除dev属性
432            for nv in del_nv_list:
433                grp.remove(nv)
434        new_tree=ET.ElementTree(new_root)
435        new_tree.write(dst_xml_list[i], encoding="utf-8")
436        i=i+1
437
438def hi_nv_split_by_product_type():
439    global g_nv_env
440    product_list=[]
441    product_list.append(g_nv_env.product_type)
442    dst_xml_list=[]
443    dst_xml_list.append(g_nv_env.combin_product_xml)
444    HI_NV_XmlSplitByProductType(g_nv_env.combin_xml, product_list, dst_xml_list)
445
446def nv_replace_val(root, str_id, str_val, bForce):
447    #print(str_id, str_val)
448
449    for grp in root:
450        for nv in grp:
451            if nv.attrib['ID'] == str_id:
452                if 0:#nv.attrib['SECURITY'] == 'PRIVATE':
453                    return -1#私有NV不允许客制化
454                else:
455                    nv.attrib['PARAM_VALUE']=str_val
456
457    return 0
458
459def HI_NV_XmlModifyByCfg(cfg_file, src_xml, dst_xml):
460    tree = ET.parse(src_xml)
461    root = tree.getroot()
462    str_id=''
463    str_val=''
464
465    with open(cfg_file) as cfg_fp:
466        for line in cfg_fp.readlines():
467            L=line.split('=')
468            if len(L) == 2:
469                key=L[0].strip()
470                val=L[1].strip()
471                if key == 'ID':
472                    int_id=hi_str_to_int(val, None)
473                    str_id=hex(int_id)
474                elif key == 'PARAM_VALUE':
475                    str_val = val
476                    nv_replace_val(root, str_id, str_val, False)
477                else:
478                    pass
479
480    new_tree = ET.ElementTree(root)
481    new_tree.write(dst_xml, encoding = "utf-8")
482
483def HI_NV_Xml2Bin(nv_tool, src_xml, dst_bin_dir, include_dir):
484    cmd_line = (nv_tool, src_xml, include_dir, dst_bin_dir)
485    print("\ncmd_line=", cmd_line)
486
487    ret = subprocess.run(cmd_line).returncode
488    if ret!=0:
489        print('error', cmd_line)
490        print("============== NV Build Failed =============")
491        sys.exit(ret)
492
493def HI_NV_HNV_Build(src_xml, dst_hnv, bin_dir):
494    global g_nv_env
495    #print("src_xml=", src_xml)
496    print("dst_hnv=", dst_hnv)
497    #print("bin_dir=", bin_dir)
498    #input("继续")
499
500    src_bin_dic = {}
501    tree = ET.parse(src_xml)
502    root = tree.getroot()
503
504    bin_file_list = os.listdir(bin_dir)
505
506    #生成bin dictionary
507    for bin_file in bin_file_list:
508        if bin_file.endswith(".bin"):
509            bin_id = bin_file[:-len('.bin')]
510            bin_file_full_name = os.path.join(bin_dir, bin_file)
511            with open(bin_file_full_name, 'rb') as fp:
512                bin = fp.read()
513                src_bin_dic[bin_id] = bin
514                #print(src_bin_dic)
515                #input("继续")
516
517    #生成工厂区NV文件_factory.hnv
518    (ret, bytearray_hnv) = hi_nv_process_mk_hnv(root, src_bin_dic, os.path.basename(dst_hnv), True)
519    factory_hnv = dst_hnv.replace('.hnv', '_factory.hnv')
520    if len(bytearray_hnv) >= g_nv_env.nv_bin_max_size:#检测NV文件大小,边界也有问题
521        print(factory_hnv, "error nv size large than nv_bin_max_size(%u)"%(g_nv_env.nv_bin_max_size))
522        exit(-1)
523    if ret == HI_ERR_SUCCESS:
524        with open(factory_hnv, 'wb+') as hnvfp:
525            hnvfp.write(bytearray_hnv)
526    g_target_hnv.append(factory_hnv)
527
528    #生成非工厂区NV文件_normal.hnv
529    (ret, bytearray_hnv) = hi_nv_process_mk_hnv(root, src_bin_dic, os.path.basename(dst_hnv), False)
530    normal_hnv = dst_hnv.replace('.hnv', '_normal.hnv')
531    if len(bytearray_hnv) >= g_nv_env.nv_bin_max_size:#检测NV文件大小,边界也有问题
532        print(normal_hnv, "error nv size large than nv_bin_max_size(%u)"%(g_nv_env.nv_bin_max_size))
533        exit(-1)
534    if ret == HI_ERR_SUCCESS:
535        with open(normal_hnv, 'wb+') as hnvfp:
536            hnvfp.write(bytearray_hnv)
537    g_target_hnv.append(normal_hnv)
538
539#def generate_pwd_nv(nv_bin_dir):
540    #cmd_line = (os.path.join(nv_bin_dir, ''.join([hex(SEC_NV_ID),'.bin'])))
541    #print('conn pwd: ', g_diag_auth_pwd)
542    #ret = os.system(cmd_line)
543    #ret = subprocess.run(cmd_line).returncode
544    #if ret!=0:
545    #    print('error:', cmd_line)
546    #    sys.exit(ret)
547
548def check_hnv_result(file_name):
549    if os.path.exists(file_name.replace('.hnv', '_factory.hnv')):
550        if os.path.exists(file_name.replace('.hnv', '_normal.hnv')):
551            return 0
552    return -1
553
554def hi_nv_modify_by_cfg():
555    print('hi_nv_modify_by_cfg')
556    global g_nv_env
557    if os.path.exists(g_nv_env.app_cfg_dir):
558        cfg_file_list = os.listdir(g_nv_env.app_cfg_dir)
559    else:
560        return 0
561    for cfg_file in cfg_file_list:
562        if cfg_file.endswith(".cfg"):
563            cfg_file = cfg_file[:-len('.cfg')]
564            print('cfg_file:', cfg_file)
565            cfg_file_full_name = os.path.join(g_nv_env.app_cfg_dir, '%s.cfg'%cfg_file)
566            cfg_xml_full_name = os.path.join(g_nv_env.temp_dir, '%s.xml'%cfg_file)
567            cfg_hnv_full_name = os.path.join(g_nv_env.hnv_dir, '%s.hnv'%g_nv_env.app_name)
568            cfg_bin_dir = os.path.join(g_nv_env.temp_dir, cfg_file)
569            if os.path.exists(cfg_bin_dir):
570                shutil.rmtree(cfg_bin_dir)
571                os.makedirs(cfg_bin_dir)
572            else:
573                os.makedirs(cfg_bin_dir)
574
575            HI_NV_XmlModifyByCfg(cfg_file_full_name, g_nv_env.combin_product_xml, cfg_xml_full_name)
576
577            HI_NV_Xml2Bin(g_nv_env.nv_tool, cfg_xml_full_name, cfg_bin_dir, g_nv_env.nv_h_dir)
578            #替换0x90安全连接NV
579            #generate_pwd_nv(cfg_bin_dir)
580            #将xml和bin文件合成hnv文件
581            HI_NV_HNV_Build(cfg_xml_full_name, cfg_hnv_full_name, cfg_bin_dir)
582            ret = check_hnv_result(cfg_hnv_full_name)
583            if ret!=0:
584                print('Build hnv ERROR:%s'%cfg_hnv_full_name)
585                sys.exit(ret)
586            print('build hnv OK:%s'%cfg_hnv_full_name)
587    print('ENDING')
588
589g_common_ver = 'bbit_'
590g_subver_name = 'common'
591def hi_nv_mk_app_subtemp_dir(product_lib_out, app_name):
592    app_subver_temp_dir = os.path.join(product_lib_out, app_name, '%s%s'%(g_common_ver, g_subver_name))
593    print('app_subver_temp_dir:%s'%app_subver_temp_dir)
594
595    if os.path.exists(product_lib_out):
596        if os.path.exists(app_subver_temp_dir):
597            shutil.rmtree(app_subver_temp_dir)
598        else:
599            os.makedirs(app_subver_temp_dir)
600            print('make app_subver_temp_dir')
601
602def hi_app_subver_list_filter(app_name, subver_list):
603    app_subver_list = []
604    for sub_name in subver_list:
605        if sub_name == app_name:
606            app_subver_list.append('common')
607        else:
608            app_subver_list.append(sub_name)
609    return app_subver_list
610
611g_root_dir = os.path.abspath(os.path.dirname(__file__))
612g_out_dir = os.path.join(g_root_dir, 'out_nv_bin')#sys.argv[2] #nv编译结果根目录,v1r1/build_tmp/HiMDL_release(该名称可变)
613g_flash_size = 4096#int(sys.argv[3])
614#g_diag_auth_pwd = 'cih518@AMR'#(sys.argv[4])
615g_ver_magic = 0#ver_magic在制作hupg的时候会重新写入,此处默认0即可,可用于单独升级NV场景下(正常无此场景),固定赋值。
616#g_user_pannel_config = user_pannel_config()
617#g_project_name = g_user_pannel_config.get_project_name()
618g_project_name = 'himdl'
619g_target_hnv = []
620
621def HI_NV_MakeMain(root_dir, product_lib_out, xml_hfile_dir, product_name, app_name, app_subver_list, hnv_dir,
622                   flash_size, ver_magic, hnv_file_name):
623    global g_common_ver
624    global g_subver_name
625    #common_ver_list = ['bbit_', 'outside_']
626    common_ver_list = ['outside_']
627    if app_subver_list == []:
628        print(app_name.upper(), 'selected 0 nv config!!!please select at least one!!!')
629        sys.exit(1)
630    for common_ver in common_ver_list:
631        g_common_ver = common_ver
632        for subver_name in app_subver_list:
633            print('current subver_name:%s'%subver_name)
634            g_subver_name = subver_name
635            ret = hi_nv_set_cfg(root_dir, product_lib_out, xml_hfile_dir, product_name, app_name, hnv_dir, flash_size,
636                                ver_magic, hnv_file_name)
637            if ret != 0:
638                continue
639            hi_nv_mk_app_subtemp_dir(product_lib_out, app_name)
640            hi_nv_combine_mss_and_app_xml()
641            hi_nv_split_by_product_type()
642            hi_nv_modify_by_cfg()
643
644def make_nv_bin(target_path = '.', target_name = 'hi3861', hnv_file_name = ''):
645    product_name_list = ['sta']
646    ''' analyse begin '''
647    app_name_list = [target_name]
648    print('product_name_list:', product_name_list)
649    for product_name in product_name_list:
650        product_out_dir = os.path.join(g_out_dir, product_name)
651        product_lib_out = os.path.join(product_out_dir, 'nv')
652        xml_hfile_dir = os.path.join(g_root_dir, 'h_file', 'nv')
653        print('xml h file:', xml_hfile_dir)
654        hnv_dir = os.path.join(product_out_dir, 'nv', 'hnv')
655        hi_nv_mk_temp_dir(product_lib_out, hnv_dir)
656        print(product_out_dir)
657        for app_name in app_name_list:
658            nv_total_list = ['demo']
659            app_subver_list = hi_app_subver_list_filter(app_name, nv_total_list)
660            print('app_subver_list:', app_subver_list)
661            HI_NV_MakeMain(g_root_dir, product_lib_out, xml_hfile_dir, product_name, app_name, app_subver_list, hnv_dir,
662                           g_flash_size, g_ver_magic, hnv_file_name)
663
664    if len(g_target_hnv) > 0:
665        for hnv in g_target_hnv:
666            shutil.copy(hnv, target_path)
667
668if __name__ == '__main__':
669    if len(sys.argv) == 4:
670        make_nv_bin(sys.argv[1], sys.argv[2], sys.argv[3])
671    else:
672        filename = sys.argv[1]
673        target_name = sys.argv[2]
674        default_target_path = os.path.join(g_root_dir, '..', '..', 'build', 'build_tmp', 'nv')
675        if os.path.exists(default_target_path) is False:
676            os.makedirs(default_target_path)
677        make_nv_bin(default_target_path, target_name, filename)
678
679