import os
import shutil
import socket

import numpy as np
import pandas as pd
import paramiko as pm
import chardet
import json
import sys
import math

addr_alloc = {
    'PCS':{'sn':'PCS','addr':2,'name':'PCS'},
    'DUI':{'sn':'Cluster','addr':18,'name':'电池堆'},
    'CU':{'sn':'Rack','addr':18, 'name':'电池簇'},
    'DX':{'sn':'Pack', 'addr':49,'name':'电芯'},
    'DWDB':{'sn':'gridmeter','addr':54, 'name':'电网电表'},
    'FZDB':{'sn':'loadmeter', 'addr':55, 'name':'负载电表'},
    'CNDB':{'sn':'bmsmeter', 'addr':56, 'name':'储能电表'},
    'KT':{'sn':'aircond', 'addr':57, 'name':'空调'},
    'TEMP':{'sn':'temp', 'addr':58,'name':'温湿度'},
    'DI':{'sn':'DI', 'addr':59,'name':'IO'},
    'XF':{'sn':'xiaofang', 'addr':60,'name':'消防主机'}
}

datatypemap = {
    1:'U8',
    2:'U16',
    3:'I16',
    4:'U32',
    5:'I32',
    6:'F32'
}

hostname='rathole.lnxall.cn'
port=65022
username='support'
private_key_path='./user-client-key'

ipkdownhost='192.168.22.104'
ipkdownport=22
ipkdownuser='jjjiang'
ipkdownpasswd='lnxall123'

sshgwprefix='ssh -oConnectionAttempts=4 -oStrictHostKeyChecking=no -i /home/support/lnxall_gateway_ssh -oTCPKeepAlive=yes -oServerAliveInterval=20 -oServerAliveCountMax=8 -p '
sshgwappend=' root@localhost '

scpgwprefix=' scp -i /home/support/lnxall_gateway_ssh -oStrictHostKeyChecking=no -P '
scpgwappend=' root@localhost:'

gwmqtthost='172.18.39.101'
gwmqttport='3883'
gwmqttuser='localuser'
gwmqttpwd='dywl@galaxy'

TOPIC_GETDEVS='T/lnxall/T001/device/getalldevs'
TOPIC_DEVTABLE='M/lnxall/T001/device/devtable'
TOPIC_GETPTS='T/lnxall/T001/device/getallpts'
TOPIC_DATA='M/lnxall/T001/device/data'

PAYLOAD_GETDEVS='{\\\"identifier\\\":\\\"getalldevs\\\",\\\"mi\\\":"1",\\\"time\\\":"1",\\\"gw_sn\\\":\\\"$SN\\\",\\\"data_type\\\":\\\"service\\\"}'
PAYLOAD_GETPTS='{\\\"devSN\\\":\\\"$DEVSN\\\",\\\"identifier\\\":\\\"getallpts\\\",\\\"mi\\\":\"1172\",\\\"time\\\":\"1\"}'

PUBCMD='mosquitto_pub -h '+gwmqtthost+' -p '+gwmqttport+' -u '+gwmqttuser+' -P '+gwmqttpwd
SUBCMD='mosquitto_sub -h '+gwmqtthost+' -p '+gwmqttport+' -u '+gwmqttuser+' -P '+gwmqttpwd

dtypes=['PCS','DUI','CU', 'DX', 'CNDB', 'DWDB', 'FZDB', 'KT', 'XF', 'DI']
colname=['TAG', '含义', '类型', '系数', '描述', '单位', '类别']

path='./北向TAG总表.xlsx'
outputiec104='./IEC104通信点位表.xlsx'
outputiec104backup='./IEC104通信点位表2.xlsx'
outputmodbus='./ModbusTCP通信点位表.xlsx'
outputmodbusbackup='./ModbusTCP通信点位表2.xlsx'

datas=pd.read_excel(path, sheet_name=dtypes)
alltagconf={}
curdev={}
curdevtype=[]

PROTO_MODBUS=0
PROTO_IEC104=1

def acqui_devtype(devsn):
    for dev in addr_alloc:
        if devsn.find(addr_alloc[dev]['sn']) >= 0:
            return dev
    return None

def compute_devscore(devsn):
    for dev in addr_alloc:
        if devsn.find(addr_alloc[dev]['sn']) >= 0:
            if dev == 'CU':
                return addr_alloc[dev]['addr'] + 1
            else:
                return addr_alloc[dev]['addr']
    return 256

def parse_alltagconf():
    for dtype in dtypes:
        data=datas[dtype]
        alltagconf[dtype] = {}
        for index,row in data.iterrows():
            tagconf={}
            for col in colname:
                if col != 'TAG':
                    tagconf[col]=row[col]
            alltagconf[dtype][row['TAG']] = tagconf
    #print(alltagconf)

def ssh_connvirtgw(client):
    client.exec_command('/home/support/ssh.py ')
    stdin, stdout, stderr = client.exec_command('cat /app/config/fac.ini')
    sshret = stdout.read()
    encod = chardet.detect(sshret)
    #print(sshret.decode(encoding=encod['encoding']))

def gen_dev_type():
    #print(curdevtype)
    outputdevtype='./devtype'
    if os.path.exists(outputdevtype):
        os.unlink(outputdevtype)
    with open(outputdevtype, 'a') as file:
        for dtype in curdevtype:
            file.write(dtype['name']+' '+dtype['alias']+' '+str(dtype['ca'])+' '+str(dtype['ycaddr'])+' '+str(dtype['yccnt'])+' '+str(dtype['yxaddr'])+' '+str(dtype['yxcnt'])+' '+str(dtype['modaddr'])+' '+str(dtype['modcnt'])+'\n')

def gen_tag_pointtable(proto=PROTO_IEC104):
    fileappend='.tag'
    if proto == PROTO_IEC104:
        outputpath=outputiec104
        tagdir='./tag'
        if os.path.exists(tagdir):
            shutil.rmtree(tagdir)
        os.mkdir(tagdir)
        if os.path.exists(outputiec104):
            os.unlink(outputiec104)
        shutil.copy(outputiec104backup, outputiec104)
    else:
        outputpath=outputmodbus
        tagdir='./tag_modbus'
        fileappend = '_MODBUS.tag'
        if os.path.exists(tagdir):
            shutil.rmtree(tagdir)
        os.mkdir(tagdir)
        if os.path.exists(outputmodbus):
            os.unlink(outputmodbus)
        shutil.copy(outputmodbusbackup, outputmodbus)

    for dev in curdev:
        pf = pd.DataFrame()
        addrs=[]
        compre=[]
        permission=[]
        dtypes=[]
        cnts=[]
        comments=[]
        with open(tagdir + '/'+dev+fileappend,'a') as file:
            sortedtag=[]
            for tag in curdev[dev]:
                sortedtag.append((tag,curdev[dev][tag]))
            sortedtag.sort(key=lambda e: e[1]['addr'])
            for tag in sortedtag:
                tag_addr = tag[1]['addr']
                tag_name = tag[0]
                if np.isnan(tag[1]['类型']):
                    tag_type = 1
                else:
                    tag_type = int(tag[1]['类型'])
                if np.isnan(tag[1]['系数']):
                    tag_k = float(1.0)
                else:
                    tag_k = float(tag[1]['系数'])
                file.write(str(tag_addr)+' '+tag_name+' '+str(tag_type)+' '+str(tag_k) + '\n')
                addrs.append(tag[1]['addr'])
                compre.append(tag[1]['含义'])
                permission.append('RO')
                dtypes.append(datatypemap[tag_type])
                cnts.append(tag[1]['单位'])
                comments.append(tag[1]['描述'])
        pf['设备']=''
        pf['寄存器地址']=addrs
        pf['名称']=compre
        pf['权限']=permission
        pf['数据类型']=dtypes
        pf['单位']=cnts
        pf['备注']=comments
        with pd.ExcelWriter(outputpath, mode='a') as writer:
            pf.to_excel(writer, sheet_name=dev,index = False)
    return

def down_ipk(
        client,
        proto=PROTO_IEC104,
        oneaddr=False
    ):
    ipkpath='/home/hxwang/jianjian/northipk/'
    subdir1='common'
    if proto==PROTO_IEC104:
        subdir2='iec104'
    else:
        subdir2='modbus-tcp'
    if oneaddr==True:
        subdir2+='-oneaddr'

    localipkdir = './ipk'
    if os.path.exists(localipkdir):
        shutil.rmtree(localipkdir)
    os.mkdir(localipkdir)

    sftpdown=pm.SFTPClient.from_transport(client.get_transport())
    commipks = sftpdown.listdir_attr(ipkpath+subdir1)
    for commipk in commipks:
        sftpdown.get(ipkpath+subdir1+'/'+commipk.filename,localipkdir+'/'+commipk.filename)
    protoipks = sftpdown.listdir_attr(ipkpath+subdir2)
    for protoipk in protoipks:
        sftpdown.get(ipkpath+subdir2+'/'+protoipk.filename,localipkdir+'/'+protoipk.filename)
    sftpdown.close()

def prototostr(proto):
    if proto==PROTO_IEC104:
        return 'IEC104'
    else:
        return 'Modbus TCP'

def oneaddrtostr(oneaddr):
    if oneaddr:
        return '是'
    else:
        return '否'

def main(
        gwsn=None,
        proto=PROTO_MODBUS,
        oneaddr=0
    ):
    if len(sys.argv) < 2:
        print('请提供部署北向的网关SN')
        return
    gwsn=sys.argv[1]
    if len(sys.argv) > 2:
        proto=int(sys.argv[2])
    if len(sys.argv) > 3:
        oneaddr=int(sys.argv[3])
    parse_alltagconf()
    print('网关SN：'+gwsn+' 北向协议：'+prototostr(proto)+' 是否使用同一公共地址：' +oneaddrtostr(oneaddr))
    client_ipkdown = pm.SSHClient()
    client_ipkdown.set_missing_host_key_policy(pm.AutoAddPolicy)
    client_ipkdown.connect(ipkdownhost,ipkdownport, ipkdownuser,ipkdownpasswd)
    print('连接ipk下载服务器成功')
    down_ipk(client_ipkdown, proto, oneaddr)

    client = pm.SSHClient()
    client.set_missing_host_key_policy(pm.AutoAddPolicy())
    try:
        client.connect(hostname, port, username, key_filename=private_key_path, timeout=20)
    except TimeoutError:
        print('连接rathole服务器失败，请检查域名端口用户名密码及网络连接')
        return
    print('连接rathole服务器成功')
    stdin, stdout, stderr = client.exec_command('/home/support/list-gateways.sh | grep ' + gwsn)
    sshret = stdout.read()
    if len(sshret) <= 0:
        print('检测网关端口失败，网关未连接rathole服务器')
        return
    encod = chardet.detect(sshret)
    gwport = sshret.decode(encoding=encod['encoding'])
    gwport=gwport[gwport.find('port: ')+len('port: '):]
    gwport=gwport[:gwport.find(',')]
    print('检测到网关端口： ', gwport)

    pubtablecmd = sshgwprefix + gwport + ' ' + sshgwappend + '\'' + PUBCMD + ' -t \"' + TOPIC_GETDEVS + '\" -m \"' + PAYLOAD_GETDEVS.replace("$SN", gwsn) + '\" --repeat 2 --repeat-delay 3 & \''
    client.exec_command(pubtablecmd)
    dtablecmd = sshgwprefix + gwport + ' ' + sshgwappend + '\''  + SUBCMD + ' -C 1 -W 10 ' + ' -t \"' + TOPIC_DEVTABLE + '\" \''
    try:
        stdin, stdout, stderr = client.exec_command(dtablecmd, timeout=10)
        sshret = stdout.read()
    except TimeoutError:
        print('虚拟网关未回复北向获取设备表消息，请确认站控版本是否支持北向')
        return
    encod = chardet.detect(sshret)
    devs = sshret.decode(encoding=encod['encoding'])

    alldevs=[]
    while True:
        if devs.find("\"dev_sn\":\"") < 0:
            break
        devs=devs[devs.find("\"dev_sn\":\"")+len("\"dev_sn\":\""):]
        alldevs.append(devs[:devs.find("\"")])
        devs=devs[devs.find("\""):]
    print('设备列表： ', alldevs)
    alldevs.sort(key=lambda e: compute_devscore(e))
    for sdev in alldevs:
        for tdev in addr_alloc:
            if sdev.find(addr_alloc[tdev]['sn']) >= 0:
                if 'cnt' not in addr_alloc[tdev]:
                    addr_alloc[tdev]['cnt'] = 1
                else:
                    addr_alloc[tdev]['cnt'] += 1
    addr_alloc['DX']['cnt']=addr_alloc['CU']['cnt']
    print('排序后设备列表： ', alldevs)

    for sdev in alldevs:
        dtype = acqui_devtype(sdev)
        if dtype == None:
            print('无法识别的设备类型', sdev)
            continue
        if dtype not in alltagconf:
            print('北向TAG总表缺失'+dtype+'设备，请补全')
            continue
        if dtype not in curdev:
            curdev[dtype]={}
            if not oneaddr:
                if dtype != 'CU':
                    curdev[dtype]['start_yx'] = 1
                    curdev[dtype]['addr_yx']=1
                    curdev[dtype]['start_yc']=16385
                    curdev[dtype]['addr_yc']=16385
                    curdev[dtype]['start_mod']=1
                    curdev[dtype]['addr_mod']=1
                else:
                    curdev[dtype]['start_yx'] = 1 + 100 * math.ceil((curdev['DUI']['addr_yx'] - 1) / 100)
                    curdev[dtype]['addr_yx']=curdev[dtype]['start_yx']
                    curdev[dtype]['start_yc'] = 16385 + 100 * math.ceil((curdev['DUI']['addr_yc'] - 1) / 100)
                    curdev[dtype]['addr_yc'] = curdev[dtype]['start_yc']
                    curdev[dtype]['start_mod']=1+ 100 * math.ceil((curdev['DUI']['addr_mod'] - 1) / 100)
                    curdev[dtype]['addr_mod'] =curdev[dtype]['start_mod']
            else:
                if len(curdevtype)<= 0:
                    curdev[dtype]['start_yx'] = 1
                    curdev[dtype]['addr_yx'] = 1
                    curdev[dtype]['start_yc'] = 17385
                    curdev[dtype]['addr_yc'] = 17385
                    curdev[dtype]['start_mod'] = 1001
                    curdev[dtype]['addr_mod'] = 1001
                else:
                    curdev[dtype]['start_yx'] = curdevtype[-1]['yxaddr']+curdevtype[-1]['yxcnt'] * addr_alloc[dtype]['cnt']
                    curdev[dtype]['addr_yx'] = curdev[dtype]['start_yx']
                    curdev[dtype]['start_yc'] =curdevtype[-1]['ycaddr'] + curdevtype[-1]['yccnt'] * addr_alloc[dtype]['cnt']
                    curdev[dtype]['addr_yc'] = curdev[dtype]['start_yc']
                    curdev[dtype]['start_mod']=curdevtype[-1]['modaddr'] + curdevtype[-1]['modcnt'] * addr_alloc[dtype]['cnt']
                    curdev[dtype]['addr_mod'] = curdev[dtype]['start_mod']

        failcnt = 0
        pubptscmd = sshgwprefix + gwport + ' ' + sshgwappend + '\'' + PUBCMD + ' -t \"' + TOPIC_GETPTS + '\" -m \"' + PAYLOAD_GETPTS.replace("$DEVSN", sdev) + '\" --repeat 3 --repeat-delay 1 & \''
        subdatacmd = sshgwprefix + gwport + ' ' + sshgwappend + '\'' + SUBCMD + ' -C 1 -W 10 -t \"' + TOPIC_DATA + '\" \''
        while True:
            client.exec_command(pubptscmd)
            stdin, stdout, stderr = client.exec_command(subdatacmd, timeout=10)
            sshret = stdout.read()
            if (len(sshret) <= 0):
                failcnt += 1
            else:
                encod = chardet.detect(sshret)
                devpts = sshret.decode(encoding=encod['encoding'])
                if devpts.find(sdev) < 0:
                    failcnt += 1
                else:
                    devjson=json.loads(devpts)
                    if 'tags' not in devjson:
                        print("设备数据无tag")
                    for tag in devjson['tags']:
                        dxflag=0
                        if tag not in alltagconf[dtype]:
                            if dtype == 'CU' and tag in alltagconf['DX']:
                                dxflag=1
                                if 'DX' not in curdev:
                                    curdev['DX'] = {}
                                    if not oneaddr:
                                        curdev['DX']['start_yx']=1
                                        curdev['DX']['addr_yx'] = 1
                                        curdev['DX']['start_yc']=16385
                                        curdev['DX']['addr_yc'] = 16385
                                        curdev['DX']['start_mod']=1
                                        curdev['DX']['addr_mod'] = 1
                                    else:
                                        curdev['DX']['start_yx'] = curdev['CU']['start_yx']+math.ceil((curdev['CU']['addr_yx']-curdev['CU']['start_yx'])/100)*100*addr_alloc[dtype]['cnt']
                                        curdev['DX']['addr_yx'] = curdev['DX']['start_yx']
                                        curdev['DX']['start_yc'] = curdev['CU']['start_yc']+math.ceil((curdev['CU']['addr_yc']-curdev['CU']['start_yc'])/100)*100*addr_alloc[dtype]['cnt']
                                        curdev['DX']['addr_yc'] = curdev['DX']['start_yc']
                                        curdev['DX']['start_mod'] = curdev['CU']['start_mod']+math.ceil((curdev['CU']['addr_mod']-curdev['CU']['start_mod'])/100)*100*addr_alloc[dtype]['cnt']
                                        curdev['DX']['addr_mod'] = curdev['DX']['start_mod']
                            else:
                                print('未识别的tag，请手动添加', dtype, tag)
                                continue
                        if dxflag > 0:
                            if tag not in curdev['DX']:
                                curdev['DX'][tag] = alltagconf['DX'][tag]
                                if proto == PROTO_IEC104:
                                    if curdev['DX'][tag]['类别'] == 1:
                                        curdev['DX'][tag]['addr'] = curdev['DX']['addr_yc']
                                        curdev['DX']['addr_yc'] += 1
                                    else:
                                        curdev['DX'][tag]['addr'] = curdev['DX']['addr_yx']
                                        curdev['DX']['addr_yx'] += 1
                                else:
                                    curdev['DX'][tag]['addr'] = curdev['DX']['addr_mod']
                                    curdev['DX']['addr_mod'] += 1
                                    if type(curdev['DX'][tag]['单位'])==str:
                                        if (not np.isnan(curdev['DX'][tag]['系数'])) and int(curdev['DX'][tag]['系数']) != 1:
                                            curdev['DX'][tag]['单位'] = str(curdev['DX'][tag]['系数'])+curdev['DX'][tag]['单位']
                        elif tag not in curdev[dtype]:
                            curdev[dtype][tag] = alltagconf[dtype][tag]
                            if proto == PROTO_IEC104:
                                if curdev[dtype][tag]['类别']==1:
                                    curdev[dtype][tag]['addr'] = curdev[dtype]['addr_yc']
                                    curdev[dtype]['addr_yc'] += 1
                                else:
                                    curdev[dtype][tag]['addr'] = curdev[dtype]['addr_yx']
                                    curdev[dtype]['addr_yx'] += 1
                            else:
                                curdev[dtype][tag]['addr'] = curdev[dtype]['addr_mod']
                                if np.isnan(curdev[dtype][tag]['类型']):
                                    curdev[dtype][tag]['类型']=1
                                if curdev[dtype][tag]['类型'] > 3:
                                    curdev[dtype]['addr_mod'] += 2
                                else:
                                    curdev[dtype]['addr_mod'] += 1
                                if type(curdev[dtype][tag]['单位'])==str:
                                    if (not np.isnan(curdev[dtype][tag]['系数'])) and int(curdev[dtype][tag]['系数']) != 1:
                                        curdev[dtype][tag]['单位'] = str(curdev[dtype][tag]['系数']) + curdev[dtype][tag]['单位']
                    break
            if failcnt >= 10:
                print("获取设备数据失败 ", sdev)
                break

        if not 'dtypeadded' in addr_alloc[dtype]:
            cdtype={}
            cdtype['name']=dtype
            cdtype['alias']=addr_alloc[dtype]['sn']
            if oneaddr:
                cdtype['ca']=1
            else:
                cdtype['ca']=addr_alloc[dtype]['addr']
            cdtype['yxaddr'] = curdev[dtype]['start_yx']
            cdtype['yxcnt'] = 100 * math.ceil((curdev[dtype]['addr_yx'] - curdev[dtype]['start_yx']) / 100)
            cdtype['ycaddr'] = curdev[dtype]['start_yc']
            cdtype['yccnt'] = 100 * math.ceil((curdev[dtype]['addr_yc'] - curdev[dtype]['start_yc']) / 100)
            cdtype['modaddr'] = curdev[dtype]['start_mod']
            cdtype['modcnt'] = 100 * math.ceil((curdev[dtype]['addr_mod'] - curdev[dtype]['start_mod']) / 100)
            addr_alloc[dtype]['dtypeadded'] = True
            curdevtype.append(cdtype)
        if 'DX' in curdev and (not 'dtypeadded' in addr_alloc['DX']):
            cdtype = {}
            cdtype['name'] = 'DX'
            cdtype['alias'] = addr_alloc['DX']['sn']
            if oneaddr:
                cdtype['ca'] = 1
            else:
                cdtype['ca'] = addr_alloc['DX']['addr']
            cdtype['yxaddr'] = curdev['DX']['start_yx']
            cdtype['yxcnt'] = 100 * math.ceil((curdev['DX']['addr_yx'] - curdev['DX']['start_yx']) / 100)
            cdtype['ycaddr'] = curdev['DX']['start_yc']
            cdtype['yccnt'] = 100 * math.ceil((curdev['DX']['addr_yc'] - curdev['DX']['start_yc']) / 100)
            cdtype['modaddr'] = curdev['DX']['start_mod']
            cdtype['modcnt'] = 100 * math.ceil((curdev['DX']['addr_mod'] - curdev['DX']['start_mod']) / 100)
            addr_alloc['DX']['dtypeadded'] = True
            curdevtype.append(cdtype)

        if 'start_yx' in curdev[dtype]:
            del curdev[dtype]['start_yx']
        if 'addr_yx' in curdev[dtype]:
            del curdev[dtype]['addr_yx']
        if 'start_yc' in curdev[dtype]:
            del curdev[dtype]['start_yc']
        if 'addr_yc' in curdev[dtype]:
            del curdev[dtype]['addr_yc']
        if 'start_mod' in curdev[dtype]:
            del curdev[dtype]['start_mod']
        if 'addr_mod' in curdev[dtype]:
            del curdev[dtype]['addr_mod']
    if 'start_yx' in curdev['DX']:
        del curdev['DX']['start_yx']
    if 'addr_yx' in curdev['DX']:
        del curdev['DX']['addr_yx']
    if 'start_yc' in curdev['DX']:
        del curdev['DX']['start_yc']
    if 'addr_yc' in curdev['DX']:
        del curdev['DX']['addr_yc']
    if 'start_mod' in curdev['DX']:
        del curdev['DX']['start_mod']
    if 'addr_mod' in curdev['DX']:
        del curdev['DX']['addr_mod']
    #print(curdev,proto)
    gen_tag_pointtable(proto)
    gen_dev_type()

    remotedir = '/home/support/jjjiang/north-auto'
    remoteipkdir = remotedir + '/ipk'
    dircmd = 'rm -rf ' + remotedir + ' && mkdir -p ' + remoteipkdir

    if proto== PROTO_IEC104:
        localdir='./tag'
        remotetagdir=remotedir + '/tag'
    else:
        localdir='./tag_modbus'
        remotetagdir=remotedir + '/tag_modbus'
    dircmd += ' && mkdir -p '+ remotetagdir
    client.exec_command(dircmd)

    sftp = pm.SFTPClient.from_transport(client.get_transport())
    files=os.listdir(localdir)
    for f in files:
        remotefile=remotetagdir+'/'+f
        sftp.put(localdir+'/'+f, remotefile)
    localdtypefile = './devtype'
    remotedtypefile=remotedir+'/devtype'
    sftp.put(localdtypefile,remotedtypefile)
    ipks=os.listdir('./ipk')
    for ipk in ipks:
        remotefile = remoteipkdir + '/' + ipk
        sftp.put('./ipk/' + ipk, remotefile)

    sftp.close()

    scpcmd = scpgwprefix + gwport + ' -r '+remotedir + ' ' + scpgwappend + '/root'
    client.exec_command(scpcmd)

    instcmd = sshgwprefix + gwport + sshgwappend + '\''+( 'mkdir -p /app/emscfg && cp -rf /root/north-auto/tag* /app/emscfg/ && ' 
                                                          'cp -f /root/north-auto/devtype /app/emscfg/ && cd /root/north-auto/ipk && '
                                                          'opkg install *redis* && opkg install *lib* && opkg install *.ipk \'')
    #print(instcmd)
    #client.exec_command(instcmd)

    client_ipkdown.close()
    client.close()
    print('完成')

if __file__ == main():
    print(sys.argv[1],sys.argv[2],sys.argv[3])
    main(gwsn=sys.argv[1],proto=sys.argv[2],oneaddr=sys.argv[3])

