Exemplo n.º 1
0
    def sendCmd(self, command):
        cmd_list = []
        self.resp = None

        # Send FW UPload request message
        cmd_list.append(["MA", self.dest_mac])
        cmd_list.append(["PW", self.idcode])
        if 'WIZ2000' in self.dev_name:
            cmd_list.append(["AP", self.set_pw.decode()])
        cmd_list.append([command, str(self.filesize)])

        print('sendCmd() cmd_list ===> ', cmd_list)

        if 'TCP' in self.sock_type:
            self.wizmsghangler = WIZMSGHandler(self.conf_sock, cmd_list, 'tcp',
                                               OP_FWUP, 2)
        elif 'UDP' in self.sock_type:
            self.wizmsghangler = WIZMSGHandler(self.conf_sock, cmd_list, 'udp',
                                               OP_FWUP, 2)
        sys.stdout.write("sendCmd(): %s\r\n" % cmd_list)

        # if no reponse from device, retry for several times.
        for i in range(4):
            # self.resp = self.wizmsghangler.parseresponse()
            self.resp = self.wizmsghangler.run()
            if self.resp is not '':
                break

        self.msleep(500)
        self.uploading_size.emit(2)
Exemplo n.º 2
0
    def __init__(self, mac_addr, id_code, cmd_list, op_code, logger):
        threading.Thread.__init__(self)
        self.logger = logger

        conf_sock = WIZUDPSock(5000, 50001)
        conf_sock.open()
        self.wizmsghangler = WIZMSGHandler(conf_sock)
        self.wizmakecmd = WIZMakeCMD()

        self.mac_addr = mac_addr
        self.id_code = id_code
        self.cmd_list = cmd_list
        self.configresult = None
        self.op_code = op_code
Exemplo n.º 3
0
    def jumpToApp(self):
        cmd_list = []
        # boot mode change: App boot mode
        cmd_list.append(["MA", self.dest_mac])
        cmd_list.append(["PW", self.idcode])
        cmd_list.append(["AB", ""])

        if 'TCP' in self.sock_type:
            self.wizmsghangler = WIZMSGHandler(self.conf_sock, cmd_list, 'tcp',
                                               OP_FWUP, 2)
        elif 'UDP' in self.sock_type:
            self.wizmsghangler = WIZMSGHandler(self.conf_sock, cmd_list, 'udp',
                                               OP_FWUP, 2)

        self.resp = self.wizmsghangler.run()

        self.uploading_size.emit(1)
        self.msleep(1000)
Exemplo n.º 4
0
    def __init__(self):
        threading.Thread.__init__(self)

        self.dest_mac = None
        self.bin_filename = None
        self.fd = None
        self.data = None
        self.client = None
        self.timer1 = None
        self.istimeout = 0
        self.serverip = None
        self.serverport = None

        self.sentbyte = 0

        conf_sock = WIZUDPSock(5000, 50001)
        conf_sock.open()
        self.wizmsghangler = WIZMSGHandler(conf_sock)
Exemplo n.º 5
0
    def __init__(self, idcode, conf_sock, sock_type):
        threading.Thread.__init__(self)

        self.dest_mac = None
        self.bin_filename = None
        self.fd = None
        self.data = None
        self.client = None
        self.timer1 = None
        self.istimeout = 0
        self.serverip = None
        self.serverport = None
        self.idcode = idcode

        self.sentbyte = 0

        self.sock_type = sock_type
        self.conf_sock = conf_sock
        conf_sock.open()
        self.wizmsghangler = WIZMSGHandler(conf_sock)
Exemplo n.º 6
0
    def Setting(self):
        self.statusbar.showMessage(' Setting device...')
        # Get each object's value
        setcmd = self.GetObjectValue()
        # self.SelectDev()

        if self.curr_dev in ONE_PORT_DEV:
            print('One port dev setting')
            # Parameter validity check
            invalid_flag = 0
            setcmd_cmd = list(setcmd.keys())
            for i in range(len(setcmd)):
                if self.wiz750cmdObj.isvalidparameter(
                        setcmd_cmd[i], setcmd.get(setcmd_cmd[i])) is False:
                    print('Invalid parameter: %s %s' %
                          (setcmd_cmd[i], setcmd.get(setcmd_cmd[i])))
                    # Invalid dialog
                    self.Dialog_invalid()
                    invalid_flag += 1
        elif self.curr_dev in TWO_PORT_DEV:
            print('Two port dev setting')
            # Parameter validity check
            invalid_flag = 0
            setcmd_cmd = list(setcmd.keys())
            for i in range(len(setcmd)):
                if self.wiz752cmdObj.isvalidparameter(
                        setcmd_cmd[i], setcmd.get(setcmd_cmd[i])) is False:
                    print('Invalid parameter: %s %s' %
                          (setcmd_cmd[i], setcmd.get(setcmd_cmd[i])))
                    # Invalid dialog
                    self.Dialog_invalid()
                    invalid_flag += 1
        # print('invalid flag: %d' % invalid_flag)
        if invalid_flag == 0:
            if self.curr_dev in ONE_PORT_DEV:
                cmd_list = self.wizmakecmd.setcommand(self.curr_mac,
                                                      list(setcmd.keys()),
                                                      list(setcmd.values()), 1)
            elif self.curr_dev in TWO_PORT_DEV:
                cmd_list = self.wizmakecmd.setcommand(self.curr_mac,
                                                      list(setcmd.keys()),
                                                      list(setcmd.values()), 2)
            print('set cmdlist: ', cmd_list)

            wizmsghangler = WIZMSGHandler(self.conf_sock)
            wizmsghangler.makecommands(cmd_list, OP_SETCOMMAND)
            wizmsghangler.sendcommands()
            wizmsghangler.parseresponse()

            self.statusbar.showMessage(' Set device complete!')
Exemplo n.º 7
0
    def Search(self):
        cmd_list = []

        self.Processing()

        # Broadcasting: Search All Devices on the network
        cmd_list = self.wizmakecmd.search_broadcast()

        self.statusbar.showMessage(' Searching devices...')

        # print(cmd_list)
        wizmsghangler = WIZMSGHandler(self.conf_sock)
        wizmsghangler.makecommands(cmd_list, OP_SEARCHALL)
        wizmsghangler.sendcommands()
        wizmsghangler.parseresponse()

        dev_name = wizmsghangler.mn_list
        mac_list = wizmsghangler.mac_list

        self.all_response = wizmsghangler.rcv_list

        # row length = the number of searched devices
        self.list_device.setRowCount(len(mac_list))

        # 검색된 장치 mac / name 출력
        for i in range(0, len(mac_list)):
            # device = "%s | %s" % (mac_list[i].decode(), dev_name[i].decode())
            self.list_device.setItem(i, 0,
                                     QTableWidgetItem(mac_list[i].decode()))
            self.list_device.setItem(i, 1,
                                     QTableWidgetItem(dev_name[i].decode()))

        # 데이터 사이즈에 따라 resize
        self.list_device.resizeColumnsToContents()
        self.list_device.resizeRowsToContents()

        # 행/열 크기 조정 disable
        self.list_device.horizontalHeader().setSectionResizeMode(2)
        self.list_device.verticalHeader().setSectionResizeMode(2)

        ## error => # self.statusbar.addPermanentWidget(self.icon_search)
        self.statusbar.showMessage(' Find %d devices' % len(mac_list))

        #### TEST: progress bar
        self.statusbar.addPermanentWidget(self.progressbar)
        self.GetProgress()
        # Remove progress bar
        self.progressbar.hide()
Exemplo n.º 8
0
def jumpToApp(mac_addr, idcode, conf_sock, sock_type):
    cmd_list = []

    conf_sock.open()
    wizmsghangler = WIZMSGHandler(conf_sock)

    # boot mode change: App boot mode
    print("[%s] Jump to app boot mode" % mac_addr)

    cmd_list.append(["MA", mac_addr])
    cmd_list.append(["PW", idcode])
    cmd_list.append(["AB", ""])
    wizmsghangler.makecommands(cmd_list, OP_FWUP)
    if sock_type == "udp":
        wizmsghangler.sendcommands()
    else:
        wizmsghangler.sendcommandsTCP()
Exemplo n.º 9
0
class MultiConfigThread(threading.Thread):
    def __init__(self, mac_addr, id_code, cmd_list, op_code, logger):
        threading.Thread.__init__(self)
        self.logger = logger

        conf_sock = WIZUDPSock(5000, 50001)
        conf_sock.open()
        self.wizmsghangler = WIZMSGHandler(conf_sock)
        self.wizmakecmd = WIZMakeCMD()

        self.mac_addr = mac_addr
        self.id_code = id_code
        self.cmd_list = cmd_list
        self.configresult = None
        self.op_code = op_code

    def set_multiip(self, host_ip, i):
        self.host_ip = host_ip
        setcmd = {}

        dst_port = "5000"
        lastnumindex = self.host_ip.rfind(".")
        lastnum = int(self.host_ip[lastnumindex + 1:])
        target_ip = self.host_ip[:lastnumindex + 1] + str(lastnum + i)
        target_gw = self.host_ip[:lastnumindex + 1] + str(1)
        self.logger.info(
            f"[Multi config] Set device IP {self.mac_addr} -> {target_ip}")
        setcmd["LI"] = target_ip
        setcmd["GW"] = target_gw
        setcmd["LP"] = dst_port
        setcmd["OP"] = "1"
        self.cmd_list = self.wizmakecmd.setcommand(self.mac_addr, self.id_code,
                                                   list(setcmd.keys()),
                                                   list(setcmd.values()))

    def run(self):
        # self.logger.info('multiset cmd_list: ', self.cmd_list)
        # self.logger.info('RUN: Multiconfig device: %s' % (mac_addr))
        self.wizmsghangler.makecommands(self.cmd_list, self.op_code)
        if SOCK_TYPE == "udp":
            self.wizmsghangler.sendcommands()
        else:
            self.wizmsghangler.sendcommandsTCP()
        if self.op_code is OP_GETFILE:
            self.wizmsghangler.parseresponse()
        else:
            self.configresult = self.wizmsghangler.checkresponse()
            # self.logger.info('\t%s: %r' % (self.mac_addr, self.configresult))
            if self.configresult < 0:
                self.logger.info(
                    f"  [{self.mac_addr}] Configuration failed. Please check the device."
                )
            else:
                if self.op_code is OP_RESET:
                    pass
                else:
                    self.wizmsghangler.get_log(self.mac_addr)
Exemplo n.º 10
0
class FWUploadThread(QThread):
    uploading_size = pyqtSignal(int)
    upload_result = pyqtSignal(int)
    error_flag = pyqtSignal(int)

    def __init__(self, conf_sock, dest_mac, idcode, set_pw, filename, filesize,
                 ipaddr, port, dev_name):
        QThread.__init__(self)

        self.dest_mac = None
        self.bin_filename = filename
        self.fd = None
        self.data = None
        self.client = None
        self.timer1 = None
        self.istimeout = 0
        self.serverip = None
        self.serverport = None
        self.sentbyte = 0
        self.dest_mac = dest_mac
        self.idcode = idcode
        self.error_noresponse = 0
        self.retrycheck = 0

        # if wiz2000
        self.dev_name = dev_name
        self.set_pw = set_pw

        self.filesize = filesize
        self.remainbytes = self.filesize

        self.conf_sock = conf_sock
        self.sock_type = '%s' % self.conf_sock

        # socket config (for TCP unicast)
        self.ip_addr = ipaddr
        self.port = port

        self.tcp_sock = None

    def setparam(self):
        self.fd = open(self.bin_filename, "rb")
        self.data = self.fd.read(-1)
        self.curr_ptr = 0
        self.fd.close()

    def myTimer(self):
        # sys.stdout.write('timer1 timeout\r\n')
        self.istimeout = 1

    def jumpToApp(self):
        cmd_list = []
        # boot mode change: App boot mode
        cmd_list.append(["MA", self.dest_mac])
        cmd_list.append(["PW", self.idcode])
        cmd_list.append(["AB", ""])

        if 'TCP' in self.sock_type:
            self.wizmsghangler = WIZMSGHandler(self.conf_sock, cmd_list, 'tcp',
                                               OP_FWUP, 2)
        elif 'UDP' in self.sock_type:
            self.wizmsghangler = WIZMSGHandler(self.conf_sock, cmd_list, 'udp',
                                               OP_FWUP, 2)

        self.resp = self.wizmsghangler.run()

        self.uploading_size.emit(1)
        self.msleep(1000)

    def sendCmd(self, command):
        cmd_list = []
        self.resp = None

        # Send FW UPload request message
        cmd_list.append(["MA", self.dest_mac])
        cmd_list.append(["PW", self.idcode])
        if 'WIZ2000' in self.dev_name:
            cmd_list.append(["AP", self.set_pw.decode()])
        cmd_list.append([command, str(self.filesize)])

        print('sendCmd() cmd_list ===> ', cmd_list)

        if 'TCP' in self.sock_type:
            self.wizmsghangler = WIZMSGHandler(self.conf_sock, cmd_list, 'tcp',
                                               OP_FWUP, 2)
        elif 'UDP' in self.sock_type:
            self.wizmsghangler = WIZMSGHandler(self.conf_sock, cmd_list, 'udp',
                                               OP_FWUP, 2)
        sys.stdout.write("sendCmd(): %s\r\n" % cmd_list)

        # if no reponse from device, retry for several times.
        for i in range(4):
            # self.resp = self.wizmsghangler.parseresponse()
            self.resp = self.wizmsghangler.run()
            if self.resp is not '':
                break

        self.msleep(500)
        self.uploading_size.emit(2)

    def run(self):
        self.setparam()
        # wiz2000: not use 'AB' command
        print('===============>> FW upload', self.dev_name)
        if 'WIZ2000' in self.dev_name:
            print('wiz2000 FW upload', self.dev_name)
            pass
        else:
            self.jumpToApp()

        if 'UDP' in self.sock_type:
            pass
        elif 'TCP' in self.sock_type:
            self.sock_close()
            self.SocketConfig()

        self.sendCmd('FW')

        if self.resp is not '' and self.resp is not None:
            resp = self.resp.decode('utf-8')
            # print('resp', resp)
            params = resp.split(':')
            sys.stdout.write('Dest IP: %s, Dest Port num: %r\r\n' %
                             (params[0], int(params[1])))
            self.serverip = params[0]
            self.serverport = int(params[1])

            self.uploading_size.emit(3)
        else:
            print(
                'No response from device. Check the network or device status.')
            self.error_flag.emit(-1)
            self.error_noresponse = -1
        try:
            self.client = TCPClient(2, params[0], int(params[1]))
        except:
            pass
        try:
            if self.error_noresponse < 0:
                pass
            else:
                # sys.stdout.write("%r\r\n" % self.client.state)
                while True:
                    if self.retrycheck > 6:
                        break

                    self.retrycheck += 1
                    if self.client.state is SOCK_CLOSE_STATE:
                        if self.timer1 is not None:
                            self.timer1.cancel()
                        cur_state = self.client.state
                        try:
                            self.client.open()
                            # sys.stdout.write('1 : %r\r\n' % self.client.getsockstate())
                            # sys.stdout.write("%r\r\n" % self.client.state)
                            if self.client.state is SOCK_OPEN_STATE:
                                sys.stdout.write('[%r] is OPEN\r\n' %
                                                 (self.serverip))
                                # sys.stdout.write('[%r] client.working_state is %r\r\n' % (self.serverip, self.client.working_state))
                                self.msleep(500)
                        except Exception as e:
                            sys.stdout.write('%r\r\n' % e)

                    elif self.client.state is SOCK_OPEN_STATE:
                        self.uploading_size.emit(4)
                        cur_state = self.client.state
                        try:
                            self.client.connect()
                            # sys.stdout.write('2 : %r' % self.client.getsockstate())
                            if self.client.state is SOCK_CONNECT_STATE:
                                sys.stdout.write('[%r] is CONNECTED\r\n' %
                                                 (self.serverip))
                                # sys.stdout.write('[%r] client.working_state is %r\r\n' % (self.serverip, self.client.working_state))
                        except Exception as e:
                            sys.stdout.write('%r\r\n' % e)

                    elif self.client.state is SOCK_CONNECT_STATE:
                        # if self.client.working_state == idle_state:
                        # sys.stdout.write('3 : %r' % self.client.getsockstate())
                        try:
                            self.uploading_size.emit(5)
                            while self.remainbytes is not 0:
                                if self.client.working_state == idle_state:
                                    if self.remainbytes >= FW_PACKET_SIZE:
                                        msg = bytearray(FW_PACKET_SIZE)
                                        msg[:] = self.data[self.curr_ptr:self.
                                                           curr_ptr +
                                                           FW_PACKET_SIZE]
                                        self.client.write(msg)
                                        self.sentbyte = FW_PACKET_SIZE
                                        # sys.stdout.write('FW_PACKET_SIZE bytes sent from at %r\r\n' % (self.curr_ptr))
                                        sys.stdout.write(
                                            '[%s] FW_PACKET_SIZE bytes sent from at %r\r\n'
                                            % (self.serverip, self.curr_ptr))
                                        self.curr_ptr += FW_PACKET_SIZE
                                        self.remainbytes -= FW_PACKET_SIZE
                                    else:
                                        self.uploading_size.emit(6)
                                        msg = bytearray(self.remainbytes)
                                        msg[:] = self.data[self.curr_ptr:self.
                                                           curr_ptr +
                                                           self.remainbytes]
                                        self.client.write(msg)
                                        # sys.stdout.write('Last %r byte sent from at %r \r\n' % (self.remainbytes, self.curr_ptr))
                                        sys.stdout.write(
                                            '[%s] Last %r byte sent from at %r \r\n'
                                            % (self.serverip, self.remainbytes,
                                               self.curr_ptr))
                                        self.curr_ptr += self.remainbytes
                                        self.remainbytes = 0
                                        self.sentbyte = self.remainbytes

                                    self.client.working_state = datasent_state

                                    self.timer1 = threading.Timer(
                                        2.0, self.myTimer)
                                    self.timer1.start()

                                elif self.client.working_state == datasent_state:
                                    # sys.stdout.write('4 : %r' % self.client.getsockstate())
                                    response = self.client.readbytes(2)
                                    if response is not None:
                                        if int(binascii.hexlify(response), 16):
                                            self.client.working_state = idle_state
                                            self.timer1.cancel()
                                            self.istimeout = 0
                                        else:
                                            print(
                                                'ERROR: No response from device. Stop FW upload...'
                                            )
                                            self.client.close()
                                            self.upload_result.emit(-1)
                                            self.terminate()

                                    if self.istimeout is 1:
                                        self.istimeout = 0
                                        self.client.working_state = idle_state
                                        self.client.close()
                                        self.upload_result.emit(-1)
                                        self.terminate()

                                self.uploading_size.emit(7)

                        except Exception as e:
                            sys.stdout.write('%r\r\n' % e)
                            response = ""
                        break

            print('retrycheck: %d' % self.retrycheck)

            if self.retrycheck > 6 or self.error_noresponse < 0:
                sys.stdout.write('Device [%s] firmware upload fail.\r\n' %
                                 (self.dest_mac))
                self.upload_result.emit(-1)
            elif self.error_noresponse >= 0:
                self.uploading_size.emit(8)
                sys.stdout.write('Device [%s] firmware upload success!\r\n' %
                                 (self.dest_mac))
                self.upload_result.emit(1)
                # send FIN packet
                self.msleep(500)
                self.client.shutdown()
                if 'TCP' in self.sock_type:
                    self.conf_sock.shutdown()
        except Exception as e:
            self.error_flag.emit(-3)
            sys.stdout.write('%r\r\n' % e)
        finally:
            pass

    def sock_close(self):
        # 기존 연결 fin
        if self.tcp_sock is not None:
            if self.tcp_sock.state is not SOCK_CLOSE_STATE:
                self.tcp_sock.shutdown()
        if self.conf_sock is not None:
            self.conf_sock.shutdown()

    def tcpConnection(self, serverip, port):
        retrynum = 0
        self.tcp_sock = TCPClient(2, serverip, port)
        print('sock state: %r' % (self.tcp_sock.state))

        while True:
            if retrynum > 6:
                break
            retrynum += 1

            if self.tcp_sock.state is SOCK_CLOSE_STATE:
                self.tcp_sock.shutdown()
                cur_state = self.tcp_sock.state
                try:
                    self.tcp_sock.open()
                    if self.tcp_sock.state is SOCK_OPEN_STATE:
                        print('[%r] is OPEN' % (serverip))
                    time.sleep(0.5)
                except Exception as e:
                    sys.stdout.write('%r\r\n' % e)
            elif self.tcp_sock.state is SOCK_OPEN_STATE:
                cur_state = self.tcp_sock.state
                try:
                    self.tcp_sock.connect()
                    if self.tcp_sock.state is SOCK_CONNECT_STATE:
                        print('[%r] is CONNECTED' % (serverip))
                except Exception as e:
                    sys.stdout.write('%r\r\n' % e)
            elif self.tcp_sock.state is SOCK_CONNECT_STATE:
                break
        if retrynum > 6:
            sys.stdout.write('Device [%s] TCP connection failed.\r\n' %
                             (serverip))
            return None
        else:
            sys.stdout.write('Device [%s] TCP connected\r\n' % (serverip))
            return self.tcp_sock

    def SocketConfig(self):
        # Broadcast
        if 'UDP' in self.sock_type:
            self.conf_sock = WIZUDPSock(5000, 50001)
            self.conf_sock.open()

        # TCP unicast
        elif 'TCP' in self.sock_type:
            print('upload_unicast: ip: %r, port: %r' %
                  (self.ip_addr, self.port))

            self.conf_sock = self.tcpConnection(self.ip_addr, self.port)

            if self.conf_sock is None:
                # self.isConnected = False
                print('TCP connection failed!: %s' % self.conf_sock)
                self.error_flag.emit(-3)
                self.terminate()
            else:
                self.isConnected = True
Exemplo n.º 11
0
    # print(args)

    wizmakecmd = WIZMakeCMD()

    if len(sys.argv) <= 4:
        print('Invalid syntax. Please refer to %s -h\n' % sys.argv[0])
        sys.exit(0)

    threads = []

    try:
        retrycount = args.retry

        conf_sock = WIZUDPSock(5000, 50001)
        conf_sock.open()
        wizmsghangler = WIZMSGHandler(conf_sock)
        cmd_list = []

        ###################################
        # Search All Devices on the network
        cmd_list = wizmakecmd.search(" ")
        # sys.stdout.write("%s\r\n" % cmd_list)
        wizmsghangler.makecommands(cmd_list, OP_SEARCHALL)
        wizmsghangler.sendcommands()
        retval = wizmsghangler.parseresponse()
        sys.stdout.write("%r devices are detected\r\n" % retval)

        ###################################
        # Set a consequent IP address and the same port number 5000 to each WIZ750SR Device
        # dst_ip = "192.168.50.50"
        dst_ip = args.targetip
Exemplo n.º 12
0
    def isvalid(self, mac_addr):
        pass

if __name__ == '__main__':
    wizmakecmd = WIZMakeCMD()

    wizarg = WIZArgParser()
    args = wizarg.config_arg()

    # wiz750cmdObj = WIZ750CMDSET(1)
    wiz752cmdObj = WIZ752CMDSET(1)

    conf_sock = WIZUDPSock(5000, 50001)
    conf_sock.open()
    wizmsghangler = WIZMSGHandler(conf_sock)

    # FUObj = FWUpload(logging.DEBUG)

    cmd_list = []
    setcmd = {}
    op_code = OP_SEARCHALL
    # print(args)

    if args.search or args.clear:
        if len(sys.argv) is not 2:
            print('Invalid argument. Please refer to %s -h\n' % sys.argv[0])
            sys.exit(0)
    else:
        if len(sys.argv) < 3:
            print('Invalid argument. Please refer to %s -h\n' % sys.argv[0])
Exemplo n.º 13
0
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.setWindowIcon(QIcon(resource_path('gui/main_icon.ico')))

        self.conf_sock = WIZUDPSock(5000, 50001)
        self.conf_sock.open()
        self.wizmsghangler = WIZMSGHandler(self.conf_sock)

        self.wiz750cmdObj = WIZ750CMDSET(1)
        self.wiz752cmdObj = WIZ752CMDSET(1)
        self.wizmakecmd = WIZMakeCMD()

        self.mac_list = []
        self.threads = []
        self.curr_mac = None
        self.curr_dev = None

        # device select event
        self.list_device.itemClicked.connect(self.devclick)

        # Button event handler
        self.btnsearch.clicked.connect(self.Search)
        self.btnsetting.clicked.connect(self.Setting)

        self.resetbtn.clicked.connect(self.OpenResetDialog)
        self.factorybtn.clicked.connect(self.OpenFactoryDialog)

        # self.fwupbtn.clicked.connect(self.FWFileOpen)
        self.fwupbtn.clicked.connect(self.NetworkCheck)

        if sys.platform.lower() == 'win32':
            self.firewallbtn.setEnabled(True)
            self.firewallbtn.clicked.connect(self.OpenFirewall)
            self.devmanagerbtn.clicked.connect(self.OpenDevManager)
        else:
            self.firewallbtn.setEnabled(False)

        self.exitbtn.clicked.connect(self.OpenExitDialog)

        # state changed event
        self.show_idcode.stateChanged.connect(self.ShowIDcode)
        self.show_connectpw.stateChanged.connect(self.ShowPW)
        self.enable_connect_pw.stateChanged.connect(self.EnablePW)
        self.at_enable.stateChanged.connect(self.EnableATmode)
        self.ip_dhcp.clicked.connect(self.CheckOPmode)
        self.ip_static.clicked.connect(self.CheckOPmode)

        # Menu event
        # self.actionSave.triggered.connect(self.SaveFile)
        # self.actionLoad.triggered.connect(self.LoadFile)
        # self.about_wiz.triggered.connect(self.OpenInfoDialog)

        # configuration save/load button
        self.savebtn.clicked.connect(self.SaveFile)
        self.loadbtn.clicked.connect(self.LoadFile)

        # OP mode event
        self.ch1_tcpclient.clicked.connect(self.OPmodeEvent)
        self.ch1_tcpserver.clicked.connect(self.OPmodeEvent)
        self.ch1_tcpmixed.clicked.connect(self.OPmodeEvent)
        self.ch1_udp.clicked.connect(self.OPmodeEvent)

        #############################################
        # Button icon set
        self.icon_save = QIcon()
        self.icon_save.addPixmap(QPixmap(resource_path('gui/save_48.ico')),
                                 QIcon.Normal, QIcon.Off)
        self.savebtn.setIcon(self.icon_save)
        self.savebtn.setIconSize(QSize(20, 20))

        self.icon_load = QIcon()
        self.icon_load.addPixmap(QPixmap(resource_path('gui/load_48.ico')),
                                 QIcon.Normal, QIcon.Off)
        self.loadbtn.setIcon(self.icon_load)
        self.loadbtn.setIconSize(QSize(20, 20))

        self.icon_ping = QIcon()
        self.icon_ping.addPixmap(QPixmap(resource_path('gui/ping_48.ico')),
                                 QIcon.Normal, QIcon.Off)
        self.devmanagerbtn.setIcon(self.icon_ping)
        self.devmanagerbtn.setIconSize(QSize(20, 20))

        self.icon_firewall = QIcon()
        self.icon_firewall.addPixmap(
            QPixmap(resource_path('gui/firewall_48.ico')), QIcon.Normal,
            QIcon.Off)
        self.firewallbtn.setIcon(self.icon_firewall)
        self.firewallbtn.setIconSize(QSize(20, 20))
        #############################################
        self.icon_search = QIcon()
        self.icon_search.addPixmap(QPixmap(resource_path('gui/search_48.ico')),
                                   QIcon.Normal, QIcon.Off)
        self.btnsearch.setIcon(self.icon_search)
        self.btnsearch.setIconSize(QSize(40, 40))

        self.icon_setting = QIcon()
        self.icon_setting.addPixmap(
            QPixmap(resource_path('gui/setting_48.ico')), QIcon.Normal,
            QIcon.Off)
        self.btnsetting.setIcon(self.icon_setting)
        self.btnsetting.setIconSize(QSize(40, 40))

        self.icon_upload = QIcon()
        self.icon_upload.addPixmap(QPixmap(resource_path('gui/upload_48.ico')),
                                   QIcon.Normal, QIcon.Off)
        self.fwupbtn.setIcon(self.icon_upload)
        self.fwupbtn.setIconSize(QSize(40, 40))

        self.icon_reset = QIcon()
        self.icon_reset.addPixmap(QPixmap(resource_path('gui/reset_48.ico')),
                                  QIcon.Normal, QIcon.Off)
        self.resetbtn.setIcon(self.icon_reset)
        self.resetbtn.setIconSize(QSize(40, 40))

        self.icon_factory = QIcon()
        self.icon_factory.addPixmap(
            QPixmap(resource_path('gui/factory_48.ico')), QIcon.Normal,
            QIcon.Off)
        self.factorybtn.setIcon(self.icon_factory)
        self.factorybtn.setIconSize(QSize(40, 40))

        self.icon_exit = QIcon()
        self.icon_exit.addPixmap(QPixmap(resource_path('gui/exit_48.ico')),
                                 QIcon.Normal, QIcon.Off)
        self.exitbtn.setIcon(self.icon_exit)
        self.exitbtn.setIconSize(QSize(40, 40))
        #############################################

        ## QThread 테스트
        #########################################################
        # self.testbtn1.clicked.connect(self.threadStart)
        # self.testbtn2.clicked.connect(self.threadStop)
        # 쓰레드 인스턴스 생성
        self.th = ProgressThread(self)
        # 쓰레드 이벤트 연결
        self.th.threadEvent.connect(self.threadEventHandler)
Exemplo n.º 14
0
class WIZWindow(QMainWindow, main_window):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.setWindowIcon(QIcon(resource_path('gui/main_icon.ico')))

        self.conf_sock = WIZUDPSock(5000, 50001)
        self.conf_sock.open()
        self.wizmsghangler = WIZMSGHandler(self.conf_sock)

        self.wiz750cmdObj = WIZ750CMDSET(1)
        self.wiz752cmdObj = WIZ752CMDSET(1)
        self.wizmakecmd = WIZMakeCMD()

        self.mac_list = []
        self.threads = []
        self.curr_mac = None
        self.curr_dev = None

        # device select event
        self.list_device.itemClicked.connect(self.devclick)

        # Button event handler
        self.btnsearch.clicked.connect(self.Search)
        self.btnsetting.clicked.connect(self.Setting)

        self.resetbtn.clicked.connect(self.OpenResetDialog)
        self.factorybtn.clicked.connect(self.OpenFactoryDialog)

        # self.fwupbtn.clicked.connect(self.FWFileOpen)
        self.fwupbtn.clicked.connect(self.NetworkCheck)

        if sys.platform.lower() == 'win32':
            self.firewallbtn.setEnabled(True)
            self.firewallbtn.clicked.connect(self.OpenFirewall)
            self.devmanagerbtn.clicked.connect(self.OpenDevManager)
        else:
            self.firewallbtn.setEnabled(False)

        self.exitbtn.clicked.connect(self.OpenExitDialog)

        # state changed event
        self.show_idcode.stateChanged.connect(self.ShowIDcode)
        self.show_connectpw.stateChanged.connect(self.ShowPW)
        self.enable_connect_pw.stateChanged.connect(self.EnablePW)
        self.at_enable.stateChanged.connect(self.EnableATmode)
        self.ip_dhcp.clicked.connect(self.CheckOPmode)
        self.ip_static.clicked.connect(self.CheckOPmode)

        # Menu event
        # self.actionSave.triggered.connect(self.SaveFile)
        # self.actionLoad.triggered.connect(self.LoadFile)
        # self.about_wiz.triggered.connect(self.OpenInfoDialog)

        # configuration save/load button
        self.savebtn.clicked.connect(self.SaveFile)
        self.loadbtn.clicked.connect(self.LoadFile)

        # OP mode event
        self.ch1_tcpclient.clicked.connect(self.OPmodeEvent)
        self.ch1_tcpserver.clicked.connect(self.OPmodeEvent)
        self.ch1_tcpmixed.clicked.connect(self.OPmodeEvent)
        self.ch1_udp.clicked.connect(self.OPmodeEvent)

        #############################################
        # Button icon set
        self.icon_save = QIcon()
        self.icon_save.addPixmap(QPixmap(resource_path('gui/save_48.ico')),
                                 QIcon.Normal, QIcon.Off)
        self.savebtn.setIcon(self.icon_save)
        self.savebtn.setIconSize(QSize(20, 20))

        self.icon_load = QIcon()
        self.icon_load.addPixmap(QPixmap(resource_path('gui/load_48.ico')),
                                 QIcon.Normal, QIcon.Off)
        self.loadbtn.setIcon(self.icon_load)
        self.loadbtn.setIconSize(QSize(20, 20))

        self.icon_ping = QIcon()
        self.icon_ping.addPixmap(QPixmap(resource_path('gui/ping_48.ico')),
                                 QIcon.Normal, QIcon.Off)
        self.devmanagerbtn.setIcon(self.icon_ping)
        self.devmanagerbtn.setIconSize(QSize(20, 20))

        self.icon_firewall = QIcon()
        self.icon_firewall.addPixmap(
            QPixmap(resource_path('gui/firewall_48.ico')), QIcon.Normal,
            QIcon.Off)
        self.firewallbtn.setIcon(self.icon_firewall)
        self.firewallbtn.setIconSize(QSize(20, 20))
        #############################################
        self.icon_search = QIcon()
        self.icon_search.addPixmap(QPixmap(resource_path('gui/search_48.ico')),
                                   QIcon.Normal, QIcon.Off)
        self.btnsearch.setIcon(self.icon_search)
        self.btnsearch.setIconSize(QSize(40, 40))

        self.icon_setting = QIcon()
        self.icon_setting.addPixmap(
            QPixmap(resource_path('gui/setting_48.ico')), QIcon.Normal,
            QIcon.Off)
        self.btnsetting.setIcon(self.icon_setting)
        self.btnsetting.setIconSize(QSize(40, 40))

        self.icon_upload = QIcon()
        self.icon_upload.addPixmap(QPixmap(resource_path('gui/upload_48.ico')),
                                   QIcon.Normal, QIcon.Off)
        self.fwupbtn.setIcon(self.icon_upload)
        self.fwupbtn.setIconSize(QSize(40, 40))

        self.icon_reset = QIcon()
        self.icon_reset.addPixmap(QPixmap(resource_path('gui/reset_48.ico')),
                                  QIcon.Normal, QIcon.Off)
        self.resetbtn.setIcon(self.icon_reset)
        self.resetbtn.setIconSize(QSize(40, 40))

        self.icon_factory = QIcon()
        self.icon_factory.addPixmap(
            QPixmap(resource_path('gui/factory_48.ico')), QIcon.Normal,
            QIcon.Off)
        self.factorybtn.setIcon(self.icon_factory)
        self.factorybtn.setIconSize(QSize(40, 40))

        self.icon_exit = QIcon()
        self.icon_exit.addPixmap(QPixmap(resource_path('gui/exit_48.ico')),
                                 QIcon.Normal, QIcon.Off)
        self.exitbtn.setIcon(self.icon_exit)
        self.exitbtn.setIconSize(QSize(40, 40))
        #############################################

        ## QThread 테스트
        #########################################################
        # self.testbtn1.clicked.connect(self.threadStart)
        # self.testbtn2.clicked.connect(self.threadStop)
        # 쓰레드 인스턴스 생성
        self.th = ProgressThread(self)
        # 쓰레드 이벤트 연결
        self.th.threadEvent.connect(self.threadEventHandler)

    ## QThread Test
    @pyqtSlot()
    def threadStart(self):
        if not self.th.isRun:
            print('Main: Thread start')
            self.th.isRun = True
            self.th.start()
            # Progress bar
            self.statusbar.addPermanentWidget(self.progressbar)
            self.GetProgress()

    @pyqtSlot()
    def threadStop(self):
        if self.th.isRun:
            print('Main: Thread Stop')
            self.th.isRun = False
            # Remove progress bar
            self.progressbar.hide()

    # 쓰레드 이벤트 핸들러
    # 장식자에 파라미터 자료형을 명시
    @pyqtSlot(int)
    def threadEventHandler(self, n):
        print('Main: threadEvent(self,' + str(n) + ')')

    #########################################################
    def CheckOPmode(self):
        if self.ip_dhcp.isChecked() is True:
            self.network_config.setEnabled(False)
        elif self.ip_dhcp.isChecked() is False:
            self.network_config.setEnabled(True)

    def EnableATmode(self):
        if self.at_enable.isChecked() is True:
            self.at_hex1.setEnabled(True)
            self.at_hex2.setEnabled(True)
            self.at_hex3.setEnabled(True)
        elif self.at_enable.isChecked() is False:
            self.at_hex1.setEnabled(False)
            self.at_hex2.setEnabled(False)
            self.at_hex3.setEnabled(False)

    def ShowIDcode(self):
        if self.show_idcode.isChecked() is True:
            self.searchcode.setEchoMode(QLineEdit.Normal)
        elif self.show_idcode.isChecked() is False:
            self.searchcode.setEchoMode(QLineEdit.Password)

    def ShowPW(self):
        if self.show_connectpw.isChecked() is True:
            self.connect_pw.setEchoMode(QLineEdit.Normal)
        elif self.show_connectpw.isChecked() is False:
            self.connect_pw.setEchoMode(QLineEdit.Password)

    def EnablePW(self):
        if self.enable_connect_pw.isChecked() is True:
            self.connect_pw.setEnabled(True)
        elif self.enable_connect_pw.isChecked() is False:
            self.connect_pw.setEnabled(False)

    def OPmodeEvent(self):
        if self.ch1_tcpclient.isChecked() is True:
            self.ch1_remote.setEnabled(True)
        elif self.ch1_tcpserver.isChecked() is True:
            self.ch1_remote.setEnabled(False)
        elif self.ch1_tcpmixed.isChecked() is True:
            self.ch1_remote.setEnabled(True)
        elif self.ch1_udp.isChecked() is True:
            self.ch1_remote.setEnabled(True)

    def GetProgress(self):
        self.completed = 0
        while self.completed < 100:
            self.completed += 0.001
            self.progressbar.setValue(self.completed)

    def Processing(self):
        # 어떤 동작을 수행중일 때는 버튼 비활성화
        self.btnsearch.setEnabled(False)
        QTimer.singleShot(1000, lambda: self.btnsearch.setEnabled(True))

    def Search(self):
        cmd_list = []

        self.Processing()

        # Broadcasting: Search All Devices on the network
        cmd_list = self.wizmakecmd.search_broadcast()

        self.statusbar.showMessage(' Searching devices...')

        # print(cmd_list)
        wizmsghangler = WIZMSGHandler(self.conf_sock)
        wizmsghangler.makecommands(cmd_list, OP_SEARCHALL)
        wizmsghangler.sendcommands()
        wizmsghangler.parseresponse()

        dev_name = wizmsghangler.mn_list
        mac_list = wizmsghangler.mac_list

        self.all_response = wizmsghangler.rcv_list

        # row length = the number of searched devices
        self.list_device.setRowCount(len(mac_list))

        # 검색된 장치 mac / name 출력
        for i in range(0, len(mac_list)):
            # device = "%s | %s" % (mac_list[i].decode(), dev_name[i].decode())
            self.list_device.setItem(i, 0,
                                     QTableWidgetItem(mac_list[i].decode()))
            self.list_device.setItem(i, 1,
                                     QTableWidgetItem(dev_name[i].decode()))

        # 데이터 사이즈에 따라 resize
        self.list_device.resizeColumnsToContents()
        self.list_device.resizeRowsToContents()

        # 행/열 크기 조정 disable
        self.list_device.horizontalHeader().setSectionResizeMode(2)
        self.list_device.verticalHeader().setSectionResizeMode(2)

        ## error => # self.statusbar.addPermanentWidget(self.icon_search)
        self.statusbar.showMessage(' Find %d devices' % len(mac_list))

        #### TEST: progress bar
        self.statusbar.addPermanentWidget(self.progressbar)
        self.GetProgress()
        # Remove progress bar
        self.progressbar.hide()

    def devclick(self):
        # get information for selected device
        for currentQTableWidgetItem in self.list_device.selectedItems():
            # print('Click info:', currentQTableWidgetItem.row(), currentQTableWidgetItem.column(), currentQTableWidgetItem.text())
            self.getdevinfo(currentQTableWidgetItem.row())

    def EnableObject(self):
        self.SelectDev()

        # 버튼 활성화
        self.resetbtn.setEnabled(True)
        self.factorybtn.setEnabled(True)
        self.fwupbtn.setEnabled(True)
        self.btnsetting.setEnabled(True)
        self.savebtn.setEnabled(True)
        self.loadbtn.setEnabled(True)

        # 창 활성화
        self.general.setEnabled(True)
        self.channel_tab.setEnabled(True)

        self.connect_pw.setEnabled(False)

        ### 포트 수에 따라 설정 탭 활성화
        if self.curr_dev in ONE_PORT_DEV:
            self.channel_tab.setTabEnabled(0, True)
            self.channel_tab.setTabEnabled(1, False)
            self.channel_tab.setTabEnabled(2, False)
            self.channel_tab.setTabEnabled(3, False)
        elif self.curr_dev in TWO_PORT_DEV:
            self.channel_tab.setTabEnabled(0, True)
            self.channel_tab.setTabEnabled(1, True)
            self.channel_tab.setTabEnabled(2, False)
            self.channel_tab.setTabEnabled(3, False)

        # MENU 활성화
        self.save_config.setEnabled(True)
        self.load_config.setEnabled(True)

    def FillInfo(self, cmdset_list):
        self.SelectDev()
        # print('FillInfo: cmdset_list', cmdset_list)

        for i in range(len(cmdset_list)):
            # device info (RO)
            if b'VR' in cmdset_list[i]:
                self.fw_version.setText(cmdset_list[i][2:].decode())
            # device info - channel 1
            if b'ST' in cmdset_list[i]:
                self.ch1_status.setText(cmdset_list[i][2:].decode())
            if b'UN' in cmdset_list[i]:
                self.ch1_uart_name.setText(cmdset_list[i][2:].decode())
            # Network - general
            if b'IM' in cmdset_list[i]:
                if cmdset_list[i][2:].decode() == '0':
                    self.ip_static.setChecked(True)
                elif cmdset_list[i][2:].decode() == '1':
                    self.ip_dhcp.setChecked(True)
            if b'LI' in cmdset_list[i]:
                self.localip.setText(cmdset_list[i][2:].decode())
                self.localip_addr = cmdset_list[i][2:].decode()
            if b'SM' in cmdset_list[i]:
                self.subnet.setText(cmdset_list[i][2:].decode())
            if b'GW' in cmdset_list[i]:
                self.gateway.setText(cmdset_list[i][2:].decode())
            if b'DS' in cmdset_list[i]:
                self.dns_addr.setText(cmdset_list[i][2:].decode())
            # etc - general
            if b'CP' in cmdset_list[i]:
                self.enable_connect_pw.setChecked(
                    int(cmdset_list[i][2:].decode()))
            if b'NP' in cmdset_list[i]:
                self.connect_pw.setText(cmdset_list[i][2:].decode())
            # command mode (AT mode)
            if b'TE' in cmdset_list[i]:
                self.at_enable.setChecked(int(cmdset_list[i][2:].decode()))
            if b'SS' in cmdset_list[i]:
                self.at_hex1.setText(cmdset_list[i][2:4].decode())
                self.at_hex2.setText(cmdset_list[i][4:6].decode())
                self.at_hex3.setText(cmdset_list[i][6:8].decode())
            # if b'SP' in cmdset_list[i]:   # search code
            if b'DG' in cmdset_list[i]:
                self.serial_debug.setChecked(int(cmdset_list[i][2:].decode()))
            # Network - channel 1
            if b'OP' in cmdset_list[i]:
                if cmdset_list[i][2:].decode() == '0':
                    self.ch1_tcpclient.setChecked(True)
                elif cmdset_list[i][2:].decode() == '1':
                    self.ch1_tcpserver.setChecked(True)
                elif cmdset_list[i][2:].decode() == '2':
                    self.ch1_tcpmixed.setChecked(True)
                elif cmdset_list[i][2:].decode() == '3':
                    self.ch1_udp.setChecked(True)
            if b'LP' in cmdset_list[i]:
                self.ch1_localport.setText(cmdset_list[i][2:].decode())
            if b'RH' in cmdset_list[i]:
                self.ch1_remoteip.setText(cmdset_list[i][2:].decode())
            if b'RP' in cmdset_list[i]:
                self.ch1_remoteport.setText(cmdset_list[i][2:].decode())
            # serial - channel 1
            if b'BR' in cmdset_list[i]:
                self.ch1_baud.setCurrentIndex(int(cmdset_list[i][2:]))
            if b'DB' in cmdset_list[i]:
                if (len(cmdset_list[i][2:]) > 2): pass
                else:
                    self.ch1_databit.setCurrentIndex(int(cmdset_list[i][2:]))
            if b'PR' in cmdset_list[i]:
                self.ch1_parity.setCurrentIndex(int(cmdset_list[i][2:]))
            if b'SB' in cmdset_list[i]:
                self.ch1_stopbit.setCurrentIndex(int(cmdset_list[i][2:]))
            if b'FL' in cmdset_list[i]:
                self.ch1_flow.setCurrentIndex(int(cmdset_list[i][2:]))
            if b'PT' in cmdset_list[i]:
                self.ch1_pack_time.setText(cmdset_list[i][2:].decode())
            if b'PS' in cmdset_list[i]:
                self.ch1_pack_size.setText(cmdset_list[i][2:].decode())
            if b'PD' in cmdset_list[i]:
                self.ch1_pack_char.setText(cmdset_list[i][2:].decode())
            # Inactive timer - channel 1
            if b'IT' in cmdset_list[i]:
                self.ch1_inact_timer.setText(cmdset_list[i][2:].decode())
            # TCP keep alive - channel 1
            if b'KA' in cmdset_list[i]:
                if cmdset_list[i][2:].decode() == '0':
                    self.ch1_keepalive_enable.setChecked(False)
                elif cmdset_list[i][2:].decode() == '1':
                    self.ch1_keepalive_enable.setChecked(True)
            if b'KI' in cmdset_list[i]:
                self.ch1_keepalive_initial.setText(cmdset_list[i][2:].decode())
            if b'KE' in cmdset_list[i]:
                self.ch1_keepalive_retry.setText(cmdset_list[i][2:].decode())
            # reconnection - channel 1
            if b'RI' in cmdset_list[i]:
                self.ch1_reconnection.setText(cmdset_list[i][2:].decode())

            # Channel 2 config (For two Port device)
            if self.curr_dev in TWO_PORT_DEV:
                # device info - channel 2
                if b'QS' in cmdset_list[i]:
                    self.ch2_status.setText(cmdset_list[i][2:].decode())
                if b'EN' in cmdset_list[i]:
                    self.ch2_uart_name.setText(cmdset_list[i][2:].decode())
                # Network - channel 2
                if b'QO' in cmdset_list[i]:
                    if cmdset_list[i][2:].decode() == '0':
                        self.ch2_tcpclient.setChecked(True)
                    elif cmdset_list[i][2:].decode() == '1':
                        self.ch2_tcpserver.setChecked(True)
                    elif cmdset_list[i][2:].decode() == '2':
                        self.ch2_tcpmixed.setChecked(True)
                    elif cmdset_list[i][2:].decode() == '3':
                        self.ch2_udp.setChecked(True)
                if b'QL' in cmdset_list[i]:
                    self.ch2_localport.setText(cmdset_list[i][2:].decode())
                if b'QH' in cmdset_list[i]:
                    self.ch2_remoteip.setText(cmdset_list[i][2:].decode())
                if b'QP' in cmdset_list[i]:
                    self.ch2_remoteport.setText(cmdset_list[i][2:].decode())
                # serial - channel 2
                if b'EB' in cmdset_list[i]:
                    if (len(cmdset_list[i][2:]) > 4):
                        pass
                    else:
                        self.ch2_baud.setCurrentIndex(int(cmdset_list[i][2:]))
                if b'ED' in cmdset_list[i]:
                    if (len(cmdset_list[i][2:]) > 2):
                        pass
                    else:
                        self.ch2_databit.setCurrentIndex(
                            int(cmdset_list[i][2:]))
                if b'EP' in cmdset_list[i]:
                    self.ch2_parity.setCurrentIndex(int(cmdset_list[i][2:]))
                if b'ES' in cmdset_list[i]:
                    self.ch2_stopbit.setCurrentIndex(int(cmdset_list[i][2:]))
                if b'EF' in cmdset_list[i]:
                    if (len(cmdset_list[i][2:]) > 2):
                        pass
                    else:
                        self.ch2_flow.setCurrentIndex(int(cmdset_list[i][2:]))
                if b'NT' in cmdset_list[i]:
                    self.ch2_pack_time.setText(cmdset_list[i][2:].decode())
                if b'NS' in cmdset_list[i]:
                    self.ch2_pack_size.setText(cmdset_list[i][2:].decode())
                if b'ND' in cmdset_list[i]:
                    self.ch2_pack_char.setText(cmdset_list[i][2:].decode())
                # Inactive timer - channel 2
                if b'RV' in cmdset_list[i]:
                    self.ch2_inact_timer.setText(cmdset_list[i][2:].decode())
                # TCP keep alive - channel 2
                if b'RA' in cmdset_list[i]:
                    if cmdset_list[i][2:].decode() == '0':
                        self.ch2_keepalive_enable.setChecked(False)
                    elif cmdset_list[i][2:].decode() == '1':
                        self.ch2_keepalive_enable.setChecked(True)
                if b'RS' in cmdset_list[i]:
                    self.ch2_keepalive_initial.setText(
                        cmdset_list[i][2:].decode())
                if b'RE' in cmdset_list[i]:
                    self.ch2_keepalive_retry.setText(
                        cmdset_list[i][2:].decode())
                # reconnection - channel 2
                if b'RR' in cmdset_list[i]:
                    self.ch2_reconnection.setText(cmdset_list[i][2:].decode())

    def getdevinfo(self, row_index):
        # print('row: ', row_index)
        self.EnableObject()

        # 선택 장치 정보 출력
        rcv_data = self.all_response
        # print('rcv_data[%d] ===> %s' % (row_index, rcv_data[row_index]))
        devinfo = rcv_data[row_index].splitlines()
        # print('devinfo %d: %s ' % (row_index, devinfo))

        self.FillInfo(devinfo)

    def Dialog_invalid(self):
        dialog = InvalidDialog()
        dialog.okbtn.clicked.connect(dialog.close)
        dialog.exec_()

    def GetObjectValue(self):
        self.SelectDev()

        setcmd = {}
        # Network - general
        setcmd['LI'] = self.localip.text()
        setcmd['SM'] = self.subnet.text()
        setcmd['GW'] = self.gateway.text()
        if self.ip_static.isChecked() is True: setcmd['IM'] = '0'
        elif self.ip_dhcp.isChecked() is True: setcmd['IM'] = '1'
        setcmd['DS'] = self.dns_addr.text()
        # etc - general
        if self.enable_connect_pw.isChecked() is True:
            setcmd['CP'] = '1'
            setcmd['NP'] = self.connect_pw.text()
        elif self.enable_connect_pw.isChecked() is False:
            setcmd['CP'] = '0'

        # command mode (AT mode)
        if self.at_enable.isChecked() is True:
            setcmd['TE'] = '1'
            setcmd['SS'] = self.at_hex1.text() + self.at_hex2.text(
            ) + self.at_hex3.text()
        elif self.at_enable.isChecked() is False:
            setcmd['TE'] = '0'

        # 'SP' 추가요망
        if self.serial_debug.isChecked() is True: setcmd['DG'] = '1'
        elif self.serial_debug.isChecked() is False: setcmd['DG'] = '0'

        # Network - channel 1
        if self.ch1_tcpclient.isChecked() is True: setcmd['OP'] = '0'
        elif self.ch1_tcpserver.isChecked() is True: setcmd['OP'] = '1'
        elif self.ch1_tcpmixed.isChecked() is True: setcmd['OP'] = '2'
        elif self.ch1_udp.isChecked() is True: setcmd['OP'] = '3'
        setcmd['LP'] = self.ch1_localport.text()
        setcmd['RH'] = self.ch1_remoteip.text()
        setcmd['RP'] = self.ch1_remoteport.text()
        # serial - channel 1
        setcmd['BR'] = str(self.ch1_baud.currentIndex())
        setcmd['DB'] = str(self.ch1_databit.currentIndex())
        setcmd['PR'] = str(self.ch1_parity.currentIndex())
        setcmd['SB'] = str(self.ch1_stopbit.currentIndex())
        setcmd['FL'] = str(self.ch1_flow.currentIndex())
        setcmd['PT'] = self.ch1_pack_time.text()
        setcmd['PS'] = self.ch1_pack_size.text()
        setcmd['PD'] = self.ch1_pack_char.text()
        # Inactive timer - channel 1
        setcmd['IT'] = self.ch1_inact_timer.text()
        # TCP keep alive - channel 1
        if self.ch1_keepalive_enable.isChecked() is True: setcmd['KA'] = '1'
        elif self.ch1_keepalive_enable.isChecked() is False: setcmd['KA'] = '0'
        setcmd['KI'] = self.ch1_keepalive_initial.text()
        setcmd['KE'] = self.ch1_keepalive_retry.text()
        # reconnection - channel 1
        setcmd['RI'] = self.ch1_reconnection.text()

        # for channel 2
        if self.curr_dev in TWO_PORT_DEV:
            # device info - channel 2
            if self.ch2_tcpclient.isChecked() is True: setcmd['QO'] = '0'
            elif self.ch2_tcpserver.isChecked() is True: setcmd['QO'] = '1'
            elif self.ch2_tcpmixed.isChecked() is True: setcmd['QO'] = '2'
            elif self.ch2_udp.isChecked() is True: setcmd['QO'] = '3'
            setcmd['QL'] = self.ch2_localport.text()
            setcmd['QH'] = self.ch2_remoteip.text()
            setcmd['QP'] = self.ch2_remoteport.text()
            # serial - channel 2
            setcmd['EB'] = str(self.ch2_baud.currentIndex())
            setcmd['ED'] = str(self.ch2_databit.currentIndex())
            setcmd['EP'] = str(self.ch2_parity.currentIndex())
            setcmd['ES'] = str(self.ch2_stopbit.currentIndex())
            setcmd['EF'] = str(self.ch2_flow.currentIndex())
            setcmd['NT'] = self.ch2_pack_time.text()
            setcmd['NS'] = self.ch2_pack_size.text()
            setcmd['ND'] = self.ch2_pack_char.text()
            # Inactive timer - channel 2
            setcmd['RV'] = self.ch2_inact_timer.text()
            # TCP keep alive - channel 2
            if self.ch2_keepalive_enable.isChecked() is True:
                setcmd['RA'] = '1'
            elif self.ch2_keepalive_enable.isChecked() is False:
                setcmd['RA'] = '0'
            setcmd['RS'] = self.ch2_keepalive_initial.text()
            setcmd['RE'] = self.ch2_keepalive_retry.text()
            # reconnection - channel 2
            setcmd['RR'] = self.ch2_reconnection.text()

        # print('setcmd:', setcmd)
        return setcmd

    def Setting(self):
        self.statusbar.showMessage(' Setting device...')
        # Get each object's value
        setcmd = self.GetObjectValue()
        # self.SelectDev()

        if self.curr_dev in ONE_PORT_DEV:
            print('One port dev setting')
            # Parameter validity check
            invalid_flag = 0
            setcmd_cmd = list(setcmd.keys())
            for i in range(len(setcmd)):
                if self.wiz750cmdObj.isvalidparameter(
                        setcmd_cmd[i], setcmd.get(setcmd_cmd[i])) is False:
                    print('Invalid parameter: %s %s' %
                          (setcmd_cmd[i], setcmd.get(setcmd_cmd[i])))
                    # Invalid dialog
                    self.Dialog_invalid()
                    invalid_flag += 1
        elif self.curr_dev in TWO_PORT_DEV:
            print('Two port dev setting')
            # Parameter validity check
            invalid_flag = 0
            setcmd_cmd = list(setcmd.keys())
            for i in range(len(setcmd)):
                if self.wiz752cmdObj.isvalidparameter(
                        setcmd_cmd[i], setcmd.get(setcmd_cmd[i])) is False:
                    print('Invalid parameter: %s %s' %
                          (setcmd_cmd[i], setcmd.get(setcmd_cmd[i])))
                    # Invalid dialog
                    self.Dialog_invalid()
                    invalid_flag += 1
        # print('invalid flag: %d' % invalid_flag)
        if invalid_flag == 0:
            if self.curr_dev in ONE_PORT_DEV:
                cmd_list = self.wizmakecmd.setcommand(self.curr_mac,
                                                      list(setcmd.keys()),
                                                      list(setcmd.values()), 1)
            elif self.curr_dev in TWO_PORT_DEV:
                cmd_list = self.wizmakecmd.setcommand(self.curr_mac,
                                                      list(setcmd.keys()),
                                                      list(setcmd.values()), 2)
            print('set cmdlist: ', cmd_list)

            wizmsghangler = WIZMSGHandler(self.conf_sock)
            wizmsghangler.makecommands(cmd_list, OP_SETCOMMAND)
            wizmsghangler.sendcommands()
            wizmsghangler.parseresponse()

            self.statusbar.showMessage(' Set device complete!')

    def SelectDev(self):
        # 선택된 장치의 mac addr / name 추출
        for currentQTableWidgetItem in self.list_device.selectedItems():
            if currentQTableWidgetItem.column() == 0:
                # mac_addr = currentQTableWidgetItem.text()
                self.curr_mac = currentQTableWidgetItem.text()
                # print('current mac addr:', self.curr_mac)
                # return mac_addr
            elif currentQTableWidgetItem.column() == 1:
                self.curr_dev = currentQTableWidgetItem.text()
                # print('current dev name:', self.curr_dev)

            self.statusbar.showMessage(' Current device [%s : %s]' %
                                       (self.curr_mac, self.curr_dev))

    def FWUpdate(self, filename):
        self.SelectDev()
        self.statusbar.showMessage(' Firmware update started. Please wait...')
        mac_addr = self.curr_mac
        print('FWUpdate %s, %s' % (mac_addr, filename))
        # FW update
        t_fwup = FWUploadThread()
        t_fwup.setparam(mac_addr, filename)
        t_fwup.jumpToApp()
        time.sleep(2)
        t_fwup.start()
        self.threads.append(t_fwup)

        for thread in self.threads:
            thread.join()  # 쓰레드 종료 대기

        self.statusbar.showMessage(' Firmware update complete!')

    def FWFileOpen(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(
            self,
            "Firmware file open",
            "",
            "Binary Files (*.bin);;All Files (*)",
            options=options)
        if fileName:
            print(fileName)
            self.FWUpdate(fileName)

    def NetworkCheck(self):
        serverip = self.localip_addr
        ping_reponse = os.system("ping " + (
            "-n 1 " if sys.platform.lower() == "win32" else "-c 1 ") +
                                 serverip)

        if ping_reponse != 0:
            self.statusbar.showMessage(' Firmware update error occured.')
            self.OpenFWUerrDialog()
            # sys.exit(0)
        else:
            self.statusbar.showMessage(
                ' Firmware update: Select App boot Firmware file. (.bin)')
            self.FWFileOpen()

    def Reset(self):
        self.statusbar.showMessage(' Reset device?')
        self.SelectDev()
        mac_addr = self.curr_mac
        cmd_list = self.wizmakecmd.reset(mac_addr)
        print('Reset: %s' % cmd_list)

        self.wizmsghangler.makecommands(cmd_list, OP_SEARCHALL)
        self.wizmsghangler.sendcommands()

        self.statusbar.showMessage(' Device reset device OK')

    def Factory(self):
        self.statusbar.showMessage(' Factory reset?')
        self.SelectDev()
        mac_addr = self.curr_mac
        cmd_list = self.wizmakecmd.factory_reset(mac_addr)
        print('Factory: %s' % cmd_list)

        self.wizmsghangler.makecommands(cmd_list, OP_SEARCHALL)
        self.wizmsghangler.sendcommands()

        self.statusbar.showMessage(' Device factory reset  OK')

    def OpenResetDialog(self):
        dialog = ResetDialog()
        # Reset btn => reset
        dialog.okbtn.clicked.connect(self.Reset)

        dialog.okbtn.clicked.connect(dialog.close)
        dialog.cancelbtn.clicked.connect(dialog.close)
        dialog.exec_()

    def OpenFactoryDialog(self):
        dialog = FactoryDialog()
        # Factory btn => factory reset
        dialog.okbtn.clicked.connect(self.Factory)

        dialog.okbtn.clicked.connect(dialog.close)
        dialog.cancelbtn.clicked.connect(dialog.close)
        dialog.exec_()

    def OpenExitDialog(self):
        dialog = ExitDialog()
        # Reset btn => reset
        dialog.okbtn.clicked.connect(lambda: self.close())

        dialog.okbtn.clicked.connect(dialog.close)
        dialog.cancelbtn.clicked.connect(dialog.close)
        dialog.exec_()

    def OpenFWUerrDialog(self):
        dialog = FWErrorDialog()
        dialog.okbtn.clicked.connect(dialog.close)
        dialog.exec_()

    ########################## MENU
    def SaveFile(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        # fileName, _ = QFileDialog.getSaveFileName(self,"Configuration Save","","Config File (.cfg);;All Files (*);;Text Files (*.txt)", options=options)
        fileName, _ = QFileDialog.getSaveFileName(
            self,
            "Configuration Save",
            "",
            "All Files (*);;Text Files (*.txt)",
            options=options)
        if fileName:
            print(fileName)
            self.SaveConfig(fileName)

    def SaveConfig(self, filename):
        setcmd = self.GetObjectValue()
        # print('SaveConfig: setcmd', setcmd)
        set_list = list(setcmd.keys())

        f = open(filename, 'w+')
        for cmd in set_list:
            cmdset = '%s%s\n' % (cmd, setcmd.get(cmd))
            f.write(cmdset)
        f.close()

    def LoadFile(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(
            self,
            "Configuration Load",
            "",
            "All Files (*);;Text Files (*.txt);;ini Files (*.ini)",
            options=options)
        if fileName:
            print(fileName)
            self.LoadConfig(fileName)

    def LoadConfig(self, data_file):
        cmd_list = []
        self.SelectDev()
        f = open(data_file, 'r')
        for line in f:
            line = re.sub('[\n]', '', line)
            if len(line) > 2:
                cmd_list.append(line.encode())
        # print('LoadConfig: cmdlist', cmd_list)

        self.FillInfo(cmd_list)

    def OpenInfoDialog(self):
        dialog = InfoDialog()
        dialog.okbtn.clicked.connect(dialog.close)
        dialog.textBrowser.setAttribute(Qt.WA_TranslucentBackground)
        dialog.exec_()

    def OpenFirewall(self):
        cmd = 'rundll32.exe shell32.dll, Control_RunDLL FireWall.cpl'
        os.system(cmd)

    def OpenDevManager(self):
        cmd = 'rundll32.exe devmgr.dll DeviceManager_Execute'
        os.system(cmd)
Exemplo n.º 15
0
class FWUploadThread(threading.Thread):
    # initialization
    def __init__(self, idcode, conf_sock, sock_type):
        threading.Thread.__init__(self)

        self.dest_mac = None
        self.bin_filename = None
        self.fd = None
        self.data = None
        self.client = None
        self.timer1 = None
        self.istimeout = 0
        self.serverip = None
        self.serverport = None
        self.idcode = idcode

        self.sentbyte = 0

        self.sock_type = sock_type
        self.conf_sock = conf_sock
        conf_sock.open()
        self.wizmsghangler = WIZMSGHandler(conf_sock)

    def setparam(self, dest_mac, binaryfile):
        self.dest_mac = dest_mac
        self.bin_filename = binaryfile
        self.fd = open(self.bin_filename, "rb")
        self.data = self.fd.read(-1)
        self.remainbytes = len(self.data)
        self.curr_ptr = 0

        sys.stdout.write("\nFirmware file size: %r\n\n" % len(self.data))

    def myTimer(self):
        # sys.stdout.write('timer1 timeout\r\n')
        self.istimeout = 1

    def jumpToApp(self):
        cmd_list = []

        # boot mode change: App boot mode
        print("[%s] Jump to app boot mode" % self.dest_mac)

        cmd_list.append(["MA", self.dest_mac])
        cmd_list.append(["PW", self.idcode])
        cmd_list.append(["AB", ""])
        self.wizmsghangler.makecommands(cmd_list, OP_FWUP)
        if self.sock_type == "udp":
            self.wizmsghangler.sendcommands()
        else:
            self.wizmsghangler.sendcommandsTCP()

            if self.conf_sock != None:
                self.conf_sock.shutdown()
            time.sleep(1)

        # print('jumpToApp cmd_list: %s' % cmd_list)

    # def run(self):
    def sendCmd(self, command):
        cmd_list = []
        self.resp = None

        # Send FW UPload request message
        cmd_list.append(["MA", self.dest_mac])
        cmd_list.append(["PW", self.idcode])
        cmd_list.append([command, str(len(self.data))])
        # sys.stdout.write("cmd_list: %s\r\n" % cmd_list)
        self.wizmsghangler.makecommands(cmd_list, OP_FWUP)

        # if no reponse from device, retry for several times.
        for i in range(3):
            if self.sock_type == "udp":
                self.wizmsghangler.sendcommands()
            else:
                self.wizmsghangler.sendcommandsTCP()
            self.resp = self.wizmsghangler.parseresponse()
            if self.resp != "":
                break
            time.sleep(1)

    def run(self):
        if self.resp != "":
            resp = self.resp.decode("utf-8")
            # print('resp', resp)
            params = resp.split(":")
            sys.stdout.write("Dest IP: %s, Dest Port num: %r\r\n" % (params[0], int(params[1])))
            self.serverip = params[0]
            self.serverport = int(params[1])

            # network reachable check
            os.system("ping " + ("-n 1 " if sys.platform.lower() == "win32" else "-c 1 ") + self.serverip)
            ping_reponse = os.system(
                "ping " + ("-n 1 " if sys.platform.lower() == "win32" else "-c 1 ") + self.serverip
            )
            # ping_reponse = os.system('ping -n 1 ' + params[0])
            if ping_reponse == 0:
                print("Device[%s] network OK" % self.dest_mac)
            else:
                print(
                    "<Ping Error>: Device[%s]: %s is unreachable.\n\tRefer --multiset or --ip options to set IP address."
                    % (self.dest_mac, self.serverip)
                )
                sys.exit(0)
        else:
            print("@@@@@ Device[%s]: No response from device. Check the network or device status." % (self.dest_mac))
            sys.exit(0)

        try:
            self.client = TCPClient(2, params[0], int(params[1]))
        except:
            pass
        self.retrycheck = 0
        try:
            # sys.stdout.write("%r\r\n" % self.client.state)
            while True:
                if self.retrycheck > 20:
                    break

                self.retrycheck += 1

                if self.client.state == SOCK_CLOSE_STATE:
                    if self.timer1 != None:
                        self.timer1.cancel()
                    cur_state = self.client.state
                    try:
                        self.client.open()
                        # sys.stdout.write('1 : %r\r\n' % self.client.getsockstate())
                        # sys.stdout.write("%r\r\n" % self.client.state)
                        if self.client.state == SOCK_OPEN_STATE:
                            # sys.stdout.write('[%r] is OPEN\r\n' % (self.serverip))
                            sys.stdout.write("[%r] is OPEN | %s\r\n" % (self.serverip, self.bin_filename))
                            # sys.stdout.write('[%r] client.working_state is %r\r\n' % (self.serverip, self.client.working_state))
                            time.sleep(0.1)
                    except Exception as e:
                        print(e)

                elif self.client.state == SOCK_OPEN_STATE:
                    cur_state = self.client.state
                    # time.sleep(2)
                    try:
                        self.client.connect()
                        # sys.stdout.write('2 : %r' % self.client.getsockstate())
                        if self.client.state == SOCK_CONNECT_STATE:
                            # sys.stdout.write('[%r] is CONNECTED\r\n' % (self.serverip))
                            sys.stdout.write("[%r] is CONNECTED | %s\r\n" % (self.serverip, self.bin_filename))
                            # sys.stdout.write('[%r] client.working_state is %r\r\n' % (self.serverip, self.client.working_state))
                            # time.sleep(1)
                    except Exception as e:
                        print(e)

                elif self.client.state == SOCK_CONNECT_STATE:
                    # if self.client.working_state == idle_state:
                    # sys.stdout.write('3 : %r' % self.client.getsockstate())
                    try:
                        while self.remainbytes != 0:
                            if self.client.working_state == idle_state:
                                if self.remainbytes >= 1024:
                                    msg = bytearray(1024)
                                    msg[:] = self.data[self.curr_ptr : self.curr_ptr + 1024]
                                    self.client.write(msg)
                                    self.sentbyte = 1024
                                    # sys.stdout.write('1024 bytes sent from at %r\r\n' % (self.curr_ptr))
                                    sys.stdout.write(
                                        "[%s] 1024 bytes sent from at %r\r\n" % (self.serverip, self.curr_ptr)
                                    )
                                    self.curr_ptr += 1024
                                    self.remainbytes -= 1024
                                else:
                                    msg = bytearray(self.remainbytes)
                                    msg[:] = self.data[self.curr_ptr : self.curr_ptr + self.remainbytes]
                                    self.client.write(msg)
                                    # sys.stdout.write('Last %r byte sent from at %r \r\n' % (self.remainbytes, self.curr_ptr))
                                    sys.stdout.write(
                                        "[%s] Last %r byte sent from at %r \r\n"
                                        % (self.serverip, self.remainbytes, self.curr_ptr)
                                    )
                                    self.curr_ptr += self.remainbytes
                                    self.remainbytes = 0
                                    self.sentbyte = self.remainbytes

                                self.client.working_state = datasent_state

                                self.timer1 = threading.Timer(2.0, self.myTimer)
                                self.timer1.start()
                            elif self.client.working_state == datasent_state:
                                # sys.stdout.write('4 : %r' % self.client.getsockstate())
                                response = self.client.readbytes(2)
                                if response != None:
                                    if int(binascii.hexlify(response), 16):
                                        self.client.working_state = idle_state
                                        self.timer1.cancel()
                                        self.istimeout = 0
                                    else:
                                        print(
                                            f"ERROR: Device[{self.dest_mac}]: No response from device. Stop FW upload..."
                                        )
                                        self.client.close()
                                        sys.exit(0)

                                if self.istimeout == 1:
                                    self.istimeout = 0
                                    self.client.working_state = idle_state
                                    self.client.close()
                                    sys.exit(0)

                    except Exception as e:
                        print(e)
                        response = ""
                    break

            if self.retrycheck > 20:
                print(f"Device [{self.dest_mac}] firmware upload fail. (file: {self.bin_filename})\r\n")
            else:
                print(f"Device [{self.dest_mac}] firmware upload success! (file: {self.bin_filename})\r\n")
            # for send FIN packet
            time.sleep(1)
            self.client.shutdown()
        except (KeyboardInterrupt, SystemExit):
            print(e)
        finally:
            pass
Exemplo n.º 16
0
def main():
    # Logger config
    logger = get_formatted_logger(logging.INFO)
    # logger = get_formatted_logger(logging.DEBUG)
    logger.propagate = False

    wizmakecmd = WIZMakeCMD()
    wizarg = WIZArgParser()
    args = wizarg.config_arg()
    # logger.info(args)

    # wiz750cmdObj = WIZ750CMDSET(1)
    wiz752cmdObj = WIZ752CMDSET(1)

    if args.unicast is None:
        SOCK_TYPE = "udp"
    else:
        SOCK_TYPE = "tcp"

    # Socket config
    if args.unicast is None:
        conf_sock = socket_config(logger, SOCK_TYPE)
    else:
        # ip & port parameter check
        ipaddr, port = get_netarg(args.unicast, logger)
        conf_sock = socket_config(logger, SOCK_TYPE, ipaddr, port)

    wizmsghangler = WIZMSGHandler(conf_sock)

    cmd_list = []
    setcmd = {}
    op_code = OP_SEARCHALL

    # Search id code init
    searchcode = " "

    if args.clear:
        logger.info("Mac list clear")
        f = open("mac_list.txt", "w")
        f.close()

    elif args.version:
        logger.info(f"WIZnet-S2E-Tool {VERSION}")

    # Configuration (single or multi)
    elif args.macaddr or args.all or args.search or args.multiset:
        if args.macaddr:
            mac_addr = args.macaddr
            # ? 00:08:DC를 생략하고 나머지만 입력해도 인식되도록 설정
            # check: length / 00:08:DC 포함 여부 /
            if "00:08:DC" not in mac_addr and len(mac_addr) == 8:
                logger.info("mac_addr:", len(mac_addr), mac_addr)
                mac_addr = "00:08:DC:" + mac_addr

            if wiz752cmdObj.isvalidparameter("MC", mac_addr) == False:
                logger.info("Invalid Mac address!\r\n")
                sys.exit(0)

        op_code = OP_SETCOMMAND
        logger.info("Device configuration start...\n")

        setcmd = make_setcmd(args)

        # search id code (parameter of 'PW')
        if args.password:
            searchcode = args.password
        else:
            searchcode = " "

        # Check parameter
        setcmd_cmd = list(setcmd.keys())
        for i in range(len(setcmd)):
            # logger.info('%r , %r' % (setcmd_cmd[i], setcmd.get(setcmd_cmd[i])))
            if wiz752cmdObj.isvalidparameter(setcmd_cmd[i],
                                             setcmd.get(
                                                 setcmd_cmd[i])) == False:
                logger.info(
                    f"{'#' * 25}\nInvalid parameter: {setcmd.get(setcmd_cmd[i])} \nPlease refer to {sys.argv[0]} -h\r\n"
                )
                sys.exit(0)

        # ALL devices config
        if args.all or args.multiset:
            if not os.path.isfile("mac_list.txt"):
                logger.info(
                    "There is no mac_list.txt file. Please search devices first from '-s/--search' option."
                )
                sys.exit(0)
            f = open("mac_list.txt", "r")
            mac_list = f.readlines()
            if len(mac_list) == 0:
                logger.info(
                    "There is no mac address. Please search devices from '-s/--search' option."
                )
                sys.exit(0)
            f.close()
            # Check parameter
            if args.multiset:
                host_ip = args.multiset
                # logger.info('Host ip: %s\n' % host_ip)
                if wiz752cmdObj.isvalidparameter("LI", host_ip) == False:
                    logger.info("Invalid IP address!\r\n")
                    sys.exit(0)

            for i in range(len(mac_list)):
                mac_addr = re.sub("[\r\n]", "", mac_list[i])
                # logger.info(mac_addr)
                if args.fwfile:
                    op_code = OP_FWUP
                    logger.info(
                        f"[Multi] Device FW upload: device {i + 1}: {mac_addr}"
                    )
                    fwup_name = "th%d_fwup" % (i)
                    fwup_name = UploadThread(conf_sock, mac_addr, searchcode,
                                             args.fwfile, logger)
                    fwup_name.start()
                else:
                    if args.multiset:
                        th_name = "th%d_config" % (i)
                        th_name = MultiConfigThread(mac_addr, searchcode,
                                                    cmd_list, OP_SETCOMMAND,
                                                    logger)
                        th_name.set_multiip(host_ip, i)
                        th_name.start()
                    elif args.getfile:
                        op_code = OP_GETFILE
                        cmd_list = wizmakecmd.get_from_file(
                            mac_addr, searchcode, args.getfile)

                        wizmsghangler.makecommands(cmd_list, op_code)
                        if SOCK_TYPE == "udp":
                            wizmsghangler.sendcommands()
                        else:
                            wizmsghangler.sendcommandsTCP()
                        wizmsghangler.parseresponse()
                    elif args.setfile:
                        op_code = OP_SETFILE
                        logger.info(
                            f"[Setfile] Device [{mac_addr}] Config from '{args.setfile}' file."
                        )
                        cmd_list = wizmakecmd.set_from_file(
                            mac_addr, searchcode, args.setfile)
                        th_setfile = MultiConfigThread(mac_addr, searchcode,
                                                       cmd_list, OP_SETFILE,
                                                       logger)
                        th_setfile.start()
                    else:
                        if args.reset:
                            op_code = OP_RESET
                            logger.info(
                                f"[Multi] Reset devices {i + 1}: {mac_addr}")
                            cmd_list = wizmakecmd.reset(mac_addr, searchcode)
                        elif args.factory:
                            op_code = OP_RESET
                            logger.info(
                                f"[Multi] Factory reset devices {i + 1}: {mac_addr}"
                            )
                            cmd_list = wizmakecmd.factory_reset(
                                mac_addr, searchcode)
                        else:
                            op_code = OP_SETCOMMAND
                            logger.info(
                                f"[Multi] Setting devices {i + 1}: {mac_addr}")
                            cmd_list = wizmakecmd.setcommand(
                                mac_addr,
                                searchcode,
                                list(setcmd.keys()),
                                list(setcmd.values()),
                            )
                        th_name = "th%d_config" % (i)
                        th_name = MultiConfigThread(mac_addr, searchcode,
                                                    cmd_list, op_code, logger)
                        th_name.start()
                        time.sleep(0.3)
                    if args.getfile:
                        logger.info(
                            f"[Multi][Getfile] Get device [{mac_addr}] info from '{args.getfile}' commands\n"
                        )
                        wizmsghangler.get_filelog(mac_addr)

        # Single device config
        else:
            if args.fwfile:
                op_code = OP_FWUP
                logger.info(f"Device [{mac_addr}] Firmware upload")
                t_fwup = FWUploadThread(searchcode, conf_sock, SOCK_TYPE)
                t_fwup.setparam(mac_addr, args.fwfile)
                t_fwup.jumpToApp()

                # socket
                if SOCK_TYPE == "udp":
                    pass
                else:
                    socket_close(conf_sock)
                    time.sleep(2)
                    # ip & port parameter check
                    ipaddr, port = get_netarg(args.unicast, logger)
                    conf_sock = socket_config(logger, SOCK_TYPE, ipaddr, port)

                t_fwup.sendCmd("FW")
                t_fwup.start()
            elif args.search:
                op_code = OP_SEARCHALL
                logger.info("Searching device...")
                cmd_list = wizmakecmd.search(searchcode)
            elif args.reset:
                op_code = OP_SETCOMMAND
                logger.info(f"Device {mac_addr} Reset")
                cmd_list = wizmakecmd.reset(mac_addr, searchcode)
            elif args.factory:
                op_code = OP_SETCOMMAND
                logger.info(f"Device {mac_addr} Factory reset")
                cmd_list = wizmakecmd.factory_reset(mac_addr, searchcode)
            elif args.setfile:
                op_code = OP_SETFILE
                logger.info(
                    f"[Setfile] Device [{mac_addr}] Config from '{args.setfile}' file."
                )
                cmd_list = wizmakecmd.set_from_file(mac_addr, searchcode,
                                                    args.setfile)
            elif args.getfile:
                op_code = OP_GETFILE
                logger.info(
                    f"[Getfile] Get device [{mac_addr}] info from '{args.getfile}' commands\n"
                )
                cmd_list = wizmakecmd.get_from_file(mac_addr, searchcode,
                                                    args.getfile)
            else:
                op_code = OP_SETCOMMAND
                logger.info(f"* Single device config: {mac_addr}")
                cmd_list = wizmakecmd.setcommand(mac_addr, searchcode,
                                                 list(setcmd.keys()),
                                                 list(setcmd.values()))

        if args.all or args.multiset:
            if args.fwfile or args.factory or args.reset:
                pass
        elif args.fwfile:
            pass
        else:
            wizmsghangler.makecommands(cmd_list, op_code)
            if SOCK_TYPE == "udp":
                wizmsghangler.sendcommands()
            else:
                wizmsghangler.sendcommandsTCP()
            if op_code is OP_SETCOMMAND:
                conf_result = wizmsghangler.checkresponse()
            else:
                conf_result = wizmsghangler.parseresponse()
    else:
        logger.info(f"\nInformation: You need to set up target device(s).\n \
           You can set the multi device in 'mac_list.txt' with the '-a' option or set single device with the '-d' option.\n \
           Please refer to {sys.argv[0]} -h\n")
        sys.exit(0)

    if args.search:
        # logger.info(wizmsghangler.mac_list)
        dev_name = wizmsghangler.devname
        mac_list = wizmsghangler.mac_list
        dev_version = wizmsghangler.version
        dev_status = wizmsghangler.devst
        ip_list = wizmsghangler.ip_list
        profiles = make_profile(mac_list, dev_name, dev_version, dev_status,
                                ip_list, args.search, logger)
        make_maclist(profiles, logger)
        logger.info(
            "\nCheck 'mac_list.txt' file for a list of searched devices.\n@ The file will be used when multi-device configuration."
        )
    elif not args.all:
        if op_code is OP_GETFILE:
            wizmsghangler.get_filelog(mac_addr)
        elif op_code is OP_SETFILE:
            logger.info(
                f"\nDevice configuration from {args.setfile} complete!")
            wizmsghangler.get_log(mac_addr)
        elif args.multiset or args.factory or args.reset:
            pass
        elif op_code is OP_SETCOMMAND:
            if conf_result < 0:
                logger.info(
                    f"\nWarning: No response from the device [{mac_addr}]. Please check the device's status."
                )
            else:
                logger.info(f"\nDevice[{mac_addr}] configuration complete!")
                wizmsghangler.get_log(mac_addr)
Exemplo n.º 17
0
class FWUploadThread(threading.Thread):
    # initialization
    # def __init__(self, log_level):
    def __init__(self):
        threading.Thread.__init__(self)

        self.dest_mac = None
        self.bin_filename = None
        self.fd = None
        self.data = None
        self.client = None
        self.timer1 = None
        self.istimeout = 0
        self.serverip = None
        self.serverport = None

        self.sentbyte = 0

        conf_sock = WIZUDPSock(5000, 50001)
        conf_sock.open()
        self.wizmsghangler = WIZMSGHandler(conf_sock)

    def setparam(self, dest_mac, binaryfile):
        self.dest_mac = dest_mac
        self.bin_filename = binaryfile
        self.fd = open(self.bin_filename, "rb")
        self.data = self.fd.read(-1)
        self.remainbytes = len(self.data)
        self.curr_ptr = 0

        sys.stdout.write("Firmware file size: %r\n\n" % len(self.data))

    def myTimer(self):
        # sys.stdout.write('timer1 timeout\r\n')
        self.istimeout = 1

    def jumpToApp(self):
        cmd_list = []
        # boot mode change: App boot mode
        cmd_list.append(["MA", self.dest_mac])
        cmd_list.append(["PW", " "])
        cmd_list.append(["AB", ""])
        self.wizmsghangler.makecommands(cmd_list, OP_FWUP)
        self.wizmsghangler.sendcommands()

    def run(self):
        cmd_list = []

        # Send FW UPload request message
        cmd_list.append(["MA", self.dest_mac])
        cmd_list.append(["PW", " "])
        cmd_list.append(["FW", str(len(self.data))])
        # sys.stdout.write("cmd_list: %s\r\n" % cmd_list)
        self.wizmsghangler.makecommands(cmd_list, OP_FWUP)
        self.wizmsghangler.sendcommands()
        resp = self.wizmsghangler.parseresponse()

        if resp is not '':
            resp = resp.decode('utf-8')
            # print('resp', resp)
            params = resp.split(':')
            sys.stdout.write('Dest IP: %s, Dest Port num: %r\r\n' %
                             (params[0], int(params[1])))
            self.serverip = params[0]
            self.serverport = int(params[1])

            # # network reachable check
            # os.system("ping " + ("-n 1 " if sys.platform.lower()=="win32" else "-c 1 ") + self.serverip)
            # ping_reponse = os.system("ping " + ("-n 1 " if sys.platform.lower()=="win32" else "-c 1 ") + self.serverip)
            # # ping_reponse = os.system('ping -n 1 ' + params[0])
            # if ping_reponse == 0:
            #     print('Device[%s] network OK' % self.dest_mac)
            # else:
            #     print('<ERROR>: Device[%s]: %s is unreachable.\n\tRefer --multiset or --ip options to set IP address.' % (self.dest_mac, self.serverip))
            #     sys.exit(0)
        else:
            print(
                'No response from device. Check the network or device status.')
            sys.exit(0)

        try:
            self.client = TCPClient(2, params[0], int(params[1]))
        except:
            pass

        try:
            # sys.stdout.write("%r\r\n" % self.client.state)
            while True:

                if self.client.state is SOCK_CLOSE_STATE:
                    if self.timer1 is not None:
                        self.timer1.cancel()
                    cur_state = self.client.state
                    try:
                        self.client.open()
                        # sys.stdout.write('1 : %r\r\n' % self.client.getsockstate())
                        # sys.stdout.write("%r\r\n" % self.client.state)
                        if self.client.state is SOCK_OPEN_STATE:
                            sys.stdout.write('[%r] is OPEN\r\n' %
                                             (self.serverip))
                            # sys.stdout.write('[%r] client.working_state is %r\r\n' % (self.serverip, self.client.working_state))
                            time.sleep(0.5)
                    except Exception as e:
                        sys.stdout.write('%r\r\n' % e)

                elif self.client.state is SOCK_OPEN_STATE:
                    cur_state = self.client.state
                    # time.sleep(2)
                    try:
                        self.client.connect()
                        # sys.stdout.write('2 : %r' % self.client.getsockstate())
                        if self.client.state is SOCK_CONNECT_STATE:
                            sys.stdout.write('[%r] is CONNECTED\r\n' %
                                             (self.serverip))
                            # sys.stdout.write('[%r] client.working_state is %r\r\n' % (self.serverip, self.client.working_state))
                            # time.sleep(1)
                    except Exception as e:
                        sys.stdout.write('%r\r\n' % e)

                elif self.client.state is SOCK_CONNECT_STATE:
                    # if self.client.working_state == idle_state:
                    # sys.stdout.write('3 : %r' % self.client.getsockstate())
                    try:
                        while self.remainbytes is not 0:
                            if self.client.working_state == idle_state:
                                if self.remainbytes >= 1024:
                                    msg = bytearray(1024)
                                    msg[:] = self.data[self.
                                                       curr_ptr:self.curr_ptr +
                                                       1024]
                                    self.client.write(msg)
                                    self.sentbyte = 1024
                                    # sys.stdout.write('1024 bytes sent from at %r\r\n' % (self.curr_ptr))
                                    sys.stdout.write(
                                        '[%s] 1024 bytes sent from at %r\r\n' %
                                        (self.serverip, self.curr_ptr))
                                    self.curr_ptr += 1024
                                    self.remainbytes -= 1024
                                else:
                                    msg = bytearray(self.remainbytes)
                                    msg[:] = self.data[self.
                                                       curr_ptr:self.curr_ptr +
                                                       self.remainbytes]
                                    self.client.write(msg)
                                    # sys.stdout.write('Last %r byte sent from at %r \r\n' % (self.remainbytes, self.curr_ptr))
                                    sys.stdout.write(
                                        '[%s] Last %r byte sent from at %r \r\n'
                                        % (self.serverip, self.remainbytes,
                                           self.curr_ptr))
                                    self.curr_ptr += self.remainbytes
                                    self.remainbytes = 0
                                    self.sentbyte = self.remainbytes

                                self.client.working_state = datasent_state

                                self.timer1 = threading.Timer(
                                    2.0, self.myTimer)
                                self.timer1.start()
                            elif self.client.working_state == datasent_state:
                                # sys.stdout.write('4 : %r' % self.client.getsockstate())
                                response = self.client.readbytes(2)
                                if response is not None:
                                    if int(binascii.hexlify(response), 16):
                                        self.client.working_state = idle_state
                                        self.timer1.cancel()
                                        self.istimeout = 0
                                    else:
                                        print(
                                            'ERROR: No response from device. Stop FW upload...'
                                        )
                                        self.client.close()
                                        sys.exit(0)

                                if self.istimeout is 1:
                                    self.istimeout = 0
                                    self.client.working_state = idle_state
                                    self.client.close()
                                    sys.exit(0)

                    except Exception as e:
                        sys.stdout.write('%r\r\n' % e)
                        response = ""
                    break
            sys.stdout.write('Device [%s] firmware upload success!\r\n' %
                             (self.dest_mac))
            # for send FIN packet
            time.sleep(2.5)
            self.client.shutdown()
        except (KeyboardInterrupt, SystemExit):
            sys.stdout.write('%r\r\n' % e)
        finally:
            pass