Пример #1
0
def test_xmodem_send_exceed_maximum_number_of_resend(mode, stream_data):
    """ XMODEM has retry parameter this function ensure that xmodem.send() will
    return False dude to the fact that resend exceeded """
    # given,
    max_resend = 16

    def generator():
        if mode == "xmodem":
            yield NAK
        else:
            yield CRC

        if mode == "xmodem":
            yield ACK

        for i in range(max_resend + 1):
            yield None

        while True:
            yield ACK

    mock = generator()

    def mock_getc(size, timeout=1):
        try:
            # python 2
            x = mock.next()
        except AttributeError:
            # python 3
            x = next(mock)
        return x

    xmodem = XMODEM(getc=mock_getc, putc=dummy_putc, mode=mode)
    # exercise
    assert not xmodem.send(stream=stream_data, retry=max_resend)
Пример #2
0
def test_xmodem_dummy_fails_send(mode):
    # given,
    modem = XMODEM(getc=dummy_getc, putc=dummy_putc, mode=mode)
    # exercise
    status = modem.send(BytesIO(b"dummy-stream"))
    # verify
    assert not status, "Expected value of status `False'"
Пример #3
0
def test_xmodem_send_fails_once_each_packet(mode, stream_data):
    """ XMODEM has retry parameter this test ensure that the number of retry for
     the whole stream_data will be higher the max_resend pro packet """
    # given,
    max_resend = 16

    def generator():
        if mode == "xmodem":
            yield NAK
        else:
            yield CRC

        while True:
            yield None
            yield ACK

    mock = generator()

    def mock_getc(size, timeout=1):
        try:
            # python 2
            x = mock.next()
        except AttributeError:
            # python 3
            x = next(mock)
        return x

    xmodem = XMODEM(getc=mock_getc, putc=dummy_putc, mode=mode)
    # exercise
    assert xmodem.send(stream=stream_data, retry=max_resend)
Пример #4
0
    def upload(self, port):
        import serial
        from xmodem import XMODEM
        import io
        # In case xmodem starts acting up
        # import logging
        # logging.basicConfig(level=logging.DEBUG)

        s = serial.Serial(port,
                          19200,
                          timeout=1,
                          parity=serial.PARITY_NONE,
                          bytesize=8,
                          stopbits=1,
                          xonxoff=0,
                          rtscts=0)

        def getc(size, timeout=1):
            return s.read(size)

        def putc(data, timeout=1):
            return s.write(data)

        modem = XMODEM(getc, putc)
        modem.send(io.BytesIO(self.input_file))
Пример #5
0
def test_xmodem_recv_bad_checksum():
    """
    Using external program for send, verify checksum fail in XMODEM.recv().
    """
    # Given,
    _, send_filename = tempfile.mkstemp()
    try:
        with open(send_filename, 'wb') as stream:
            fill_binary_data(stream)
        proc = subprocess.Popen(
            (send_prog, '--xmodem', '--verbose', send_filename),
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            bufsize=0)

        getc = functools.partial(_proc_getc_fail_16bit_checksum, proc=proc)
        putc = functools.partial(_proc_putc, proc=proc)

        xmodem = XMODEM(getc, putc)
        recv_stream = BytesIO()

        # Exercise,
        status = xmodem.recv(recv_stream, timeout=5, crc_mode=1)

        # Verify,
        assert status == recv_stream.tell()
        verify_binary_data(recv_stream, padding=b'\x1a')
        proc.wait()
        assert proc.returncode == 0

    finally:
        os.unlink(send_filename)
Пример #6
0
def xmodem_dl(port, baudrate, file):
	ser = serial.Serial(port,baudrate,timeout=1)
	def getc(size, timeout=1):
	    time.sleep(0.05)
	    return ser.read(size) or None
	
	def putc(data, timeout=1):
	    time.sleep(0.05)
	    return ser.write(data)
	putc('version\r\n')
	time.sleep(0.1)
	old_ver = getc(30)
	print('----old FW version is:'+old_ver)
	time.sleep(0.1)
	putc('updata\r\n')
	time.sleep(0.1)
	c = getc(13)
	print(c)
	modem = XMODEM(getc, putc,mode = 'xmodem1k')
	stream = open(file, 'rb')
	state = modem.send(stream)
	if state:
		dl_str = getc(100)
		print(dl_str)
		print("--success--")
	else:
		dl_str = getc(10)
		print("--fail--")
Пример #7
0
def test_xmodem_send_fails_once_each_packet(mode, stream_data):
    """ Verify send(retry=n) under 'n' transfer failures of single block. """
    # given,
    max_resend = 1

    def getc_generator():
        if mode == 'xmodem':
            yield NAK
        else:
            # xmodem1k
            yield CRC

        while True:
            # fail
            yield None

            # succeed
            yield ACK

    mock = getc_generator()

    def mock_getc(size, timeout=1):
        return next(mock)

    xmodem = XMODEM(getc=mock_getc, putc=dummy_putc, mode=mode)

    # exercise
    result = xmodem.send(stream=stream_data, retry=max_resend)

    # verify
    assert result
Пример #8
0
def test_xmodem_send_fails_once_each_packet(mode, stream_data):
    """ XMODEM has retry parameter this test ensure that the number of retry for
     the whole stream_data will be higher the max_resend pro packet """
    # given,
    max_resend = 16

    def generator():
        if mode == 'xmodem':
            yield NAK
        else:
            yield CRC

        while True:
            yield None
            yield ACK

    mock = generator()

    def mock_getc(size, timeout=1):
        try:
            # python 2
            x = mock.next()
        except AttributeError:
            # python 3
            x = next(mock)
        return x

    xmodem = XMODEM(getc=mock_getc, putc=dummy_putc, mode=mode)
    # exercise
    assert xmodem.send(stream=stream_data, retry=max_resend)
Пример #9
0
def test_xmodem_dummy_fails_send(mode):
    # given,
    modem = XMODEM(getc=dummy_getc, putc=dummy_putc, mode=mode)
    # exercise
    status = modem.send(BytesIO(b'dummy-stream'))
    # verify
    assert not status, ("Expected value of status `False'")
Пример #10
0
def test_xmodem_bad_mode():
    # given,
    mode = 'XXX'
    modem = XMODEM(getc=dummy_getc, putc=dummy_putc, mode=mode)
    # exercise
    with pytest.raises(ValueError):
        status = modem.send(BytesIO(b'dummy-stream'))
Пример #11
0
def test_xmodem_send():
    """ Using external program for receive, verify XMODEM.send(). """
    # Given,
    _, recv_filename = tempfile.mkstemp()
    try:
        proc = subprocess.Popen(
            (recv_prog, '--xmodem', '--verbose', recv_filename),
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            bufsize=0)

        getc = functools.partial(_proc_getc, proc=proc)
        putc = functools.partial(_proc_putc, proc=proc)

        xmodem = XMODEM(getc, putc, pad=b'\xbb')
        stream = fill_binary_data(BytesIO())

        # Exercise,
        status = xmodem.send(stream, timeout=5, callback=_send_callback)

        # Verify,
        assert status is True
        verify_binary_data(stream, padding=b'\xbb')
        verify_binary_data(open(recv_filename, 'rb'), padding=b'\xbb')
        proc.wait()
        assert proc.returncode == 0

    finally:
        if os.path.isfile(recv_filename):
            os.unlink(recv_filename)
Пример #12
0
def test_xmodem_send_exceed_maximum_number_of_resend(mode, stream_data):
    """ Verify send(retry=n) after 'n' transfer failures of single block. """

    # given,
    max_resend = 3

    def getc_generator():
        if mode == 'xmodem':
            yield NAK
        else:
            # xmodem1k
            yield CRC

        if mode == 'xmodem':
            yield ACK

        for i in range(max_resend + 1):
            yield None

        while True:
            yield ACK

    mock = getc_generator()

    def mock_getc(size, timeout=1):
        return next(mock)

    xmodem = XMODEM(getc=mock_getc, putc=dummy_putc, mode=mode)

    # exercise
    result = xmodem.send(stream=stream_data, retry=max_resend)

    # verify
    assert not result
Пример #13
0
def test_xmodem_bad_mode():
    # given,
    mode = "XXX"
    modem = XMODEM(getc=dummy_getc, putc=dummy_putc, mode=mode)
    # exercise
    with pytest.raises(ValueError):
        status = modem.send(BytesIO(b"dummy-stream"))
Пример #14
0
def test_xmodem_send():
    """ Using external program for receive, verify XMODEM.send(). """
    # Given,
    _, recv_filename = tempfile.mkstemp()
    try:
        proc = subprocess.Popen(
            (recv_prog, '--xmodem', '--verbose', recv_filename),
            stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=0)

        getc = functools.partial(_proc_getc, proc=proc)
        putc = functools.partial(_proc_putc, proc=proc)

        xmodem = XMODEM(getc, putc, pad=b'\xbb')
        stream = fill_binary_data(BytesIO())

        # Exercise,
        status = xmodem.send(stream, timeout=5, callback=_send_callback)

        # Verify,
        assert status is True
        verify_binary_data(stream, padding=b'\xbb')
        verify_binary_data(open(recv_filename, 'rb'), padding=b'\xbb')
        proc.wait()
        assert proc.returncode == 0

    finally:
        if os.path.isfile(recv_filename):
            os.unlink(recv_filename)
Пример #15
0
    def run(self):
        try:
            if self.tSerial.pause():
                try:
                    if self.cmd:
                        # Send command and wait for ACK(\x15)
                        self.tSerial.write_no_wait("{}\n".format(self.cmd))
                        tm_bgn = time.time()
                        while time.time() - tm_bgn < self.timeout:
                            data = self.tSerial.read_no_wait()
                            if data and data in ["\x15", "C"]:
                                break
                            time.sleep(0.2)
                        else:
                            return

                    # Start xmodem send
                    self.modem = XMODEM(self.getc, self.putc, mode='xmodem')
                    with open(self.path, 'rb') as fd:
                        self.status = self.modem.send(fd,
                                                      callback=self.callback)
                finally:
                    self.tSerial.resume()
        finally:
            self.doneUpdate.emit(self.status)
Пример #16
0
def test_xmodem_recv_bad_checksum():
    """
    Using external program for send, verify checksum fail in XMODEM.recv().
    """
    # Given,
    _, send_filename = tempfile.mkstemp()
    try:
        with open(send_filename, 'wb') as stream:
            fill_binary_data(stream)
        proc = subprocess.Popen(
            (send_prog, '--xmodem', '--verbose', send_filename),
            stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=0)

        getc = functools.partial(_proc_getc_fail_16bit_checksum, proc=proc)
        putc = functools.partial(_proc_putc, proc=proc)

        xmodem = XMODEM(getc, putc)
        recv_stream = BytesIO()

        # Exercise,
        status = xmodem.recv(recv_stream, timeout=5, crc_mode=1)

        # Verify,
        assert status == recv_stream.tell()
        verify_binary_data(recv_stream, padding=b'\x1a')
        proc.wait()
        assert proc.returncode == 0

    finally:
        os.unlink(send_filename)
Пример #17
0
def test_xmodem_send_exceed_maximum_number_of_resend(mode, stream_data):
    """ Verify send(retry=n) after 'n' transfer failures of single block. """

    # given,
    max_resend = 3

    def getc_generator():
        if mode == 'xmodem':
            yield NAK
        else:
            # xmodem1k
            yield CRC

        if mode == 'xmodem':
            yield ACK

        for i in range(max_resend + 1):
            yield None

        while True:
            yield ACK

    mock = getc_generator()

    def mock_getc(size, timeout=1):
        return next(mock)

    xmodem = XMODEM(getc=mock_getc, putc=dummy_putc, mode=mode)

    # exercise
    result = xmodem.send(stream=stream_data, retry=max_resend)

    # verify
    assert not result
Пример #18
0
def test_xmodem_send_exceed_maximum_number_of_resend(mode, stream_data):
    """ XMODEM has retry parameter this function ensure that xmodem.send() will
    return False dude to the fact that resend exceeded """
    # given,
    max_resend = 16

    def generator():
        if mode == 'xmodem':
            yield NAK
        else:
            yield CRC

        if mode == 'xmodem':
            yield ACK

        for i in range(max_resend + 1):
            yield None

        while True:
            yield ACK

    mock = generator()

    def mock_getc(size, timeout=1):
        try:
            # python 2
            x = mock.next()
        except AttributeError:
            # python 3
            x = next(mock)
        return x

    xmodem = XMODEM(getc=mock_getc, putc=dummy_putc, mode=mode)
    # exercise
    assert not xmodem.send(stream=stream_data, retry=max_resend)
Пример #19
0
def test_xmodem_send_fails_once_each_packet(mode, stream_data):
    """ Verify send(retry=n) under 'n' transfer failures of single block. """
    # given,
    max_resend = 1

    def getc_generator():
        if mode == 'xmodem':
            yield NAK
        else:
            # xmodem1k
            yield CRC

        while True:
            # fail
            yield None

            # succeed
            yield ACK

    mock = getc_generator()

    def mock_getc(size, timeout=1):
        return next(mock)

    xmodem = XMODEM(getc=mock_getc, putc=dummy_putc, mode=mode)

    # exercise
    result = xmodem.send(stream=stream_data, retry=max_resend)

    # verify
    assert result
Пример #20
0
def firmwareUpdater():
    def getc(size, timeout=1):
        return ser.read(size) or None

    def putc(data, timeout=1):
        ser.write(data) or None

    response.set_header('Content-Type', 'application/json')
    upload = request.files.get('file')
    upload.save("fw.bin", overwrite=True)
    for x in range(2):
        ser = serial.Serial(Serial_Port, timeout=1)
        ser.write(b'RST}')
        sleep(2)

        ser.close()
    ser = serial.Serial(Serial_Port, timeout=1)

    modem = XMODEM(getc, putc)
    f = open('fw.bin', 'rb')
    ser.flushInput()
    ser.flushOutput()
    status = modem.send(f)
    sleep(2)
    ser.flushInput()
    ser.flushOutput()
    ser.write(b'b')
    f.close()
    ser.close()
    return None
Пример #21
0
class xferXmodem(xferBase):
    maxpayload = -1  # Don't care
    increment = 128
    last_ok = 0
    mode = "xmodem"

    def __init__(self, terminal, params={}):
        super().__init__(terminal, params)

    def connect(self, chip):
        def getc(size, timeout=10):
            ret = self.term.read(size)
            return ret or None

        def putc(data, timeout=10):
            return self.term.write(data)  # note that this ignores the timeout

        self.modem = XMODEM(getc, putc, mode=self.mode)
        return super().connect(chip)

    def _write(self, destaddr, buffer, callback=None):
        def wrap_callback(total_packets, success_count, error_count):
            if self.last_ok != success_count and success_count != 0:
                if callback:
                    callback(total_packets * self.increment,
                             success_count * self.increment, self.increment)
            self.last_ok = success_count

        if not isinstance(buffer, io.IOBase):
            buffer = io.BytesIO(buffer)

        ln = self.stream_size(buffer)
        return self.modem.send(buffer, retry=128, callback=wrap_callback)

    def _read(self, srcaddr, length, callback=None):
        def wrap_callback(total_packets, success_count, error_count,
                          packet_size):
            if self.last_ok != success_count and success_count != 0:
                if callback:
                    callback(length, success_count * packet_size, packet_size)
            self.last_ok = success_count

        stream = io.BytesIO()
        #HACK: Check if this stuff is merged: https://github.com/tehmaze/xmodem/pull/53
        spec = inspect.getargspec(self.modem.recv)
        if "callback" in spec.args:
            self.modem.recv(stream,
                            crc_mode=0,
                            retry=128,
                            callback=wrap_callback)
        else:
            print(
                "WARN: No progressbar will be shown, because xmodem library is too old"
            )
            print(
                "WARN: Please update (pip install --upgrade xmodem) to see progressbar during readdout"
            )
            self.modem.recv(stream, crc_mode=0, retry=128)
        return stream.getvalue()
Пример #22
0
 def __init__(self, port, speed, binpath=None, debug=False):
     self.speed = speed
     self.baud = self.BAUD[speed]
     self.port = port
     self.xm = XMODEM(self.getc, self.putc, "xmodem1k", "\xff")
     self.binpath = binpath or BIN_PATH
     self.tag = 0x1000
     self.debug = debug
Пример #23
0
def xm_write_page(samba, page_address, data):
    adrstr = hex(page_address)[2:].zfill(8)
    samba.xm_init_sf(adrstr)
    sendbuf = BytesIO(data)
    modem = XMODEM(samba.xm_getc, samba.xm_putc)
    if not modem.send(sendbuf, quiet=True):
        raise IOError("XMODEM Transfer Failure")
    sendbuf.close()
Пример #24
0
    def connect(self, chip):
        def getc(size, timeout=10):
            ret = self.term.read(size)
            return ret or None

        def putc(data, timeout=10):
            return self.term.write(data)  # note that this ignores the timeout

        self.modem = XMODEM(getc, putc, mode=self.mode)
        return super().connect(chip)
Пример #25
0
    def _sendfile(self, filename, callback=None):
        """ Send a file to the device using xmodem. """
        def getc(size, timeout=1):
            self.sport.timeout = timeout
            return self.sport.read(size)

        def putc(data, timeout=1):
            self.sport.writeTimeout = timeout
            return self.sport.write(data)

        def mycallback(total_packets, success_count, error_count):
            if cb:
                cb(total_packets, success_count, error_count, file_packets)

        self.previous_line = ''

        def statuscallback(total_packets, success_count, error_count,
                           file_packets):
            #global previous_line
            this_line = " %d%%  %d err\r" % (total_packets * 100 /
                                             file_packets, error_count)
            if this_line != self.previous_line:
                self.previous_line = this_line
                sys.stdout.write(this_line)
                sys.stdout.flush()

        self.proc.sendline('')
        self.proc.expect('=>')
        self._log(2, "xmdm")
        self.proc.sendline('xmdm')
        sleep(1.0)

        self.sport.close()
        self.sport = serial.Serial(port=self.tty,
                                   baudrate=self.baudrate,
                                   bytesize=8,
                                   parity='N',
                                   stopbits=1,
                                   timeout=None,
                                   xonxoff=0,
                                   rtscts=0)
        modem = XMODEM(getc, putc)

        if callback:
            cb = callback
        else:
            if self.verbosity >= 1:
                cb = statuscallback
            else:
                cb = None
        file_packets = (os.path.getsize(self.filename) - 1) / 128 + 1
        result = modem.send(open(filename, 'rb'), callback=mycallback)
        self._log(2, "xmodem result = " + str(result))
        self.proc = pexpect.fdpexpect.fdspawn(self.sport, logfile=self.logfile)
Пример #26
0
def download(outfile):
    print("Starting download")
    # Initiate xmodem download
    exchangeCommand("dx", "CTRL+C to cancel.\r\n")

    xm = XMODEM(getc, putc)
    print("Downloading", end="", flush=True)
    n = xm.recv(outfile, crc_mode=False, retry=102, quiet=False)
    print("")  # newline

    print("Bytes received: " + str(n))
    return n
Пример #27
0
class xferXmodem(xferBase):
    increment = 128
    mode = "xmodem"

    def __init__(self, terminal):
        super().__init__(terminal)

    def connect(self, chip):
        ser = self.term.ser

        def getc(size, timeout=10):
            ret = ser.read(size)
            return ret or None

        def putc(data, timeout=10):
            return ser.write(data)  # note that this ignores the timeout

        self.modem = XMODEM(getc, putc, mode=self.mode)
        return super().connect(chip)

    def _send(self, stream, destaddr, desc="Sending stream"):
        total = self.stream_size(stream)
        terminal = self.term
        increment = self.increment
        terminal.progress_start(desc, total)
        self.last_ok = 0

        def callback(total_packets, success_count, error_count):
            if self.last_ok != success_count and success_count != 0:
                terminal.progress_update(total_packets * increment,
                                         success_count * increment, increment)
            self.last_ok = success_count

        ret = self.modem.send(stream, retry=128, callback=callback)
        terminal.progress_end()
        return ret

    def _recv(self, stream, srcaddr, total, desc='Receiving stream'):
        terminal = self.term
        increment = self.increment
        #terminal.progress_start(desc, total)
        self.last_ok = 0

        def callback(total_packets, success_count, error_count):
            if self.last_ok != success_count and success_count != 0:
                terminal.progress_update(total_packets * increment,
                                         success_count * increment, increment)
            self.last_ok = success_count

        #FixMe: modem.recv doesn't support callback mechanism
        ret = self.modem.recv(stream, crc_mode=0, retry=128)
        #terminal.progress_end()
        return ret
Пример #28
0
def upload(ser,
           path,
           flashsize,
           bootloadersize,
           shouldverify=True,
           destructive=False):
    run = True
    while run:
        try:
            f = open(path, "rb")
        except IOError:
            CHK(False, "'%s': can't open file" % path, 5)

        # upload command
        if destructive:
            ser.write('d')
        else:
            ser.write('u')

        def ser_write(msg, timeout=1):
            ser.setWriteTimeout(timeout)
            return ser.write(msg)

        def ser_read(size, timeout=1):
            ser.setTimeout(timeout)
            return ser.read(size)

        modem = XMODEM(ser_read, ser_write, pad='\xff')
        modem.send(f)
        f.close()

        ser.setTimeout(0)
        ser.setWriteTimeout(0)

        if shouldverify:
            run = not verify(ser, path, flashsize, bootloadersize, destructive)
            if run:  #verify failed
                input_ok = False
                while not input_ok:
                    tmp = raw_input("Verify failed! Retry? [Y|n]")
                    if len(tmp) == 0 or tmp.upper() == 'Y':
                        input_ok = True
                    elif tmp.upper() == 'N':
                        input_ok = True
                        CHK(
                            False,
                            "Verify failed! Uploaded programm may be inconsistent!",
                            6)
        else:
            run = False
    # reset command
    ser.write('r')
Пример #29
0
 def fw_update(self):
     ser = self.myserial
     modem = XMODEM(self.getc, self.putc)
     # stream = open('/home/pi/share/fw/0bb_stg1_pkg1-0m_L56A0200_to_L58A0204.bin', 'rb')
     stream = open('/home/pi/share/fw/0bb_stg2_L56A0200_to_L58A0204.bin', 'rb')
     rmutils.write(ser, 'AT+UFWUPD=3')
     rmutils.wait_urc(ser, 20, self.com_port)
     modem.send(stream)
     stream.close()
     ser.flushOutput()
     rmutils.wait_urc(ser, 20, self.com_port)
     # print(stream)
     rmutils.write(ser, 'AT+UFWINSTALL')
     rmutils.write(ser, 'AT+UFWINSTALL?')
Пример #30
0
    def __init__(self, port_number):
        self.port = config.PORT_NAME[port_number]
        self.serial = serial.Serial(
            port=self.port,
            baudrate=115200,
            parity=serial.PARITY_NONE,
            stopbits=serial.STOPBITS_ONE,
            bytesize=serial.EIGHTBITS,
            timeout=1)

        # setup xmodem for image transfers
        self.modem = XMODEM(self.getc, self.putc)
    
        self.logger = app_api.logging_setup("UART")
Пример #31
0
def download(filename):
    modem = XMODEM(getc, putc)
    cmd = 'upload ' + filename
    send_cmd(cmd)  # b'upload trend.log\n'
    receive_line()  # b'Start receiving now.\r\n'
    stream = open(FILENAME, 'wb')
    print('*Start receiving (XMODEM-CRC)')
    ser.flushInput()
    modem.recv(stream, crc_mode=1)
    line = receive_line()  # b'28822 Bytes Transmitted.\r\n'
    size = int(line.split()[0])
    stream.truncate(size)
    stream.close()
    print('*downloaded ' + filename + ' (' + str(size) + ' bytes)')
    return size
Пример #32
0
def update_keyboard(keylist, port, rotation):
    key_identifier = bytearray.fromhex('DEAD')
    key_data = []
    binary_file = 'binary_file.bin'
    max_keys = 12

    # key_data has (keycode, width, height, bitmap)
    for keys in keylist:
        key_data.append(
            (keys.get_keycode(), keys.get_width(), keys.get_height(),
             Image.frombytes(mode='L',
                             data=bytes.fromhex(keys.get_bitmap()),
                             size=(keys.get_width(),
                                   keys.get_height())).rotate(rotation)))

    # Generate the binary file to send
    with open(
            binary_file, 'wb'
    ) as f:  # Should erase existing files when it's opened for writing
        count = 0
        for index, image in zip(range(max_keys), key_data):
            f.write(key_identifier)
            f.write(count.to_bytes(1, 'big'))
            count += 1
            f.write((int(image[0], 16)).to_bytes(1, 'big'))
            f.write(image[1].to_bytes(1, 'big'))
            f.write(image[2].to_bytes(1, 'big'))
            f.write(image[3].tobytes())

    # Send the file
    ser = serial.Serial(port, timeout=1, baudrate=230400)

    # Not reading
    def getc(size, timeout=1):
        return ser.read(size)

    # Data to send
    def putc(data, timeout=1):
        ser.write(data)
        time.sleep(0.001)  # delay for safety reasons

    modem = XMODEM(getc, putc)
    stream = open(binary_file, 'rb')
    send_result = modem.send(stream, timeout=2, retry=2)

    ser.close()

    return send_result
Пример #33
0
def upload(infile):
    print("Starting upload")
    time_start = datetime.datetime.now()
    # Initiate xmodem download
    exchangeCommand("ux", "READY. Please start uploading.\r\n", atEnd=False)

    xm = XMODEM(getc, putc)
    print("Uploading", end="", flush=True)
    n = xm.send(infile, retry=102, quiet=False)
    print("")  # newline
    duration = (datetime.datetime.now() - time_start).total_seconds()
    if n:
        print("Upload completed with success in ", duration, "seconds")
    else:
        print("Upload error")
    return n
Пример #34
0
def main():
    if len(sys.argv) < 3:
        print("Serial or font file not specified")
        return

    path = sys.argv[1]
    if not Path(path).exists():
        print("Not found:", sys.argv[1])
        return
    serial = Serial(path, 115200)
    serial.write(CMD)
    serial.read(len(CMD))

    path = sys.argv[2]
    if not Path(path).exists():
        return

    with open(path, 'rb') as f:

        def getc(size, timeout=0):
            return serial.read(size)

        def putc(data, timeout=0):
            return serial.write(data)

        def xmodem_callback(total_packets, _success_count, _fail_count):
            print('%d packets sent' % total_packets, end='\r')

        XMODEM(getc, putc).send(f,
                                retry=0,
                                timeout=1,
                                callback=xmodem_callback)
    print('\nTransfer complete')
Пример #35
0
def xmodem_payload(fl, chunksize=0, welcome=b"boot: host: Hit 'X' for xmodem upload\n"):
    poll_for_invite(welcome)
    print("Sending payload")

    stream = open(fl, 'rb')
    modem = XMODEM(getc, putc)
    if chunksize==0:
        ret = modem.send(stream, retry=16)
    else:
        while True:
            data = stream.read(chunksize)
            if (not data):
                    break
            data = io.BytesIO(data)
            ret = modem.send(data, retry=16)
            poll_for_invite(welcome)            
    print("Delivered!")
Пример #36
0
def xmodem_send(serial, stream, timeout):
    rtscts = serial.rtscts
    serial.rtscts = 0

    # From https://pypi.org/project/xmodem/.
    def getc(size, timeout=timeout):
        res = serial.read(size) or None
        return res

    def putc(data, timeout=timeout):
        res = serial.write(data)  # note that this ignores the timeout
        return res

    xmodem = XMODEM(getc, putc)
    xmodem.send(stream)

    serial.rtscts = rtscts
Пример #37
0
 def send_file(self, filename):
     self.logger.warning('Sending file %s', filename)
     self.cloud.network.modem.serial_port.write_timeout = 20
     self.cloud.network.modem.command('+UFWUPD',
                                      '3',
                                      expected='ONGOING',
                                      timeout=60)
     time.sleep(5)
     fd = open(filename, 'rb')
     self.logger.warning('Writing file to serial port')
     modem = XMODEM(self.xgetc, self.xputc)
     sent_success = modem.send(fd, retry=25, timeout=90)
     fd.close()
     if not sent_success:
         raise UpdaterException('Failed to send file via xmodem')
     self.logger.debug('Done writing')
     time.sleep(1)
     return True
Пример #38
0
def upload(ser, path, flashsize, bootloadersize, shouldverify=True, destructive=False):
    run = True
    while run:
        try:
            f = open(path, "rb")
        except IOError:
            CHK(False, "'%s': can't open file" % path, 5)

        # upload command
        if destructive:
            ser.write("d")
        else:
            ser.write("u")

        def ser_write(msg, timeout=1):
            ser.setWriteTimeout(timeout)
            return ser.write(msg)

        def ser_read(size, timeout=1):
            ser.setTimeout(timeout)
            return ser.read(size)

        modem = XMODEM(ser_read, ser_write, pad="\xff")
        modem.send(f)
        f.close()

        ser.setTimeout(0)
        ser.setWriteTimeout(0)

        if shouldverify:
            run = not verify(ser, path, flashsize, bootloadersize, destructive)
            if run:  # verify failed
                input_ok = False
                while not input_ok:
                    tmp = raw_input("Verify failed! Retry? [Y|n]")
                    if len(tmp) == 0 or tmp.upper() == "Y":
                        input_ok = True
                    elif tmp.upper() == "N":
                        input_ok = True
                        CHK(False, "Verify failed! Uploaded programm may be inconsistent!", 6)
        else:
            run = False
    # reset command
    ser.write("r")
Пример #39
0
  def __init__(self, line, speed, image) :
    self.con = serial.Serial(line, speed, timeout=0.01)
    self.lock = RLock()
    def auto_print() :
      while True :
        with self.lock :
          sys.stdout.write(self.con.read(32))
        time.sleep(0.01)
    self.thread = Thread(target=auto_print)
    self.thread.daemon = True
    self.thread.start()
    self.command("")
    self.command("down")

    while True :
      self.command("load")

      with self.lock :
        def getc(size, timeout=1.0):
          start = time.time()

          data = ""
          while len(data) < size :
            data += self.con.read()
            now = time.time()

            if now-start > timeout :
              break
          return data
        def putc(data, timeout=1.0):
          self.con.write(data)

        modem = XMODEM(getc, putc)
        stream = file(image, 'rb')
        ret = modem.send(stream, retry=4, timeout=1.0)
        if ret == True :
          break

    self.command("run")
    with self.lock :
      while True :
        if "succeed" in self.con.readline() :
          break
Пример #40
0
    def _sendfile(self, filename, callback=None):
        """ Send a file to the device using xmodem. """
        def getc(size, timeout=1):
            self.sport.timeout = timeout
            return self.sport.read(size)
        def putc(data, timeout=1):
            self.sport.writeTimeout = timeout
            return self.sport.write(data)
        
        def mycallback(total_packets, success_count, error_count):
            if cb:
                cb(total_packets, success_count, error_count, file_packets)

        self.previous_line = ''
        def statuscallback(total_packets, success_count, error_count, file_packets):
            #global previous_line
            this_line = " %d%%  %d err\r" % (total_packets*100/file_packets, error_count)
            if this_line != self.previous_line:
                self.previous_line = this_line
                sys.stdout.write(this_line)
                sys.stdout.flush()

        self.proc.sendline('')
        self.proc.expect('=>')
        self._log(2, "xmdm")
        self.proc.sendline('xmdm')
        sleep(1.0)

        self.sport.close()
        self.sport = serial.Serial(port=self.tty, baudrate=self.baudrate, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0)
        modem = XMODEM(getc, putc)

        if callback:
            cb = callback
        else:
            if self.verbosity >= 1:
                cb = statuscallback
            else:
                cb = None        
        file_packets = (os.path.getsize(self.filename)-1)/128+1
        result = modem.send(open(filename, 'rb'), callback=mycallback)
        self._log(2, "xmodem result = " + str(result))
        self.proc = pexpect.fdpexpect.fdspawn(self.sport, logfile=self.logfile)
Пример #41
0
class ThreadXmodem(QThread):
    procUpdate = pyqtSignal(int, int, int)
    doneUpdate = pyqtSignal(bool)

    def __init__(self, session, cmd, timeout, path):
        super(ThreadXmodem, self).__init__()
        self.serial = session.envs.get('SERIAL')
        self.tSerial = session.serial
        self.cmd = cmd
        self.path = path
        self.timeout = float(timeout) / 1000
        self.modem = None
        self.status = False

    # noinspection PyUnusedLocal
    def getc(self, size, timeout=1):
        return self.serial.read(size)

    # noinspection PyUnusedLocal
    def putc(self, data, timeout=1):
        self.serial.write(data)

    def callback(self, packages, success, error):
        self.procUpdate.emit(packages, success, error)

    def run(self):
        try:
            if self.tSerial.pause():
                try:
                    if self.cmd:
                        # Send command and wait for ACK(\x15)
                        self.tSerial.write_no_wait("{}\n".format(self.cmd))
                        tm_bgn = time.time()
                        while time.time() - tm_bgn < self.timeout:
                            data = self.tSerial.read_no_wait()
                            if data and data in ["\x15", "C"]:
                                break
                            time.sleep(0.2)
                        else:
                            return

                    # Start xmodem send
                    self.modem = XMODEM(self.getc, self.putc, mode='xmodem')
                    with open(self.path, 'rb') as fd:
                        self.status = self.modem.send(fd,
                                                      callback=self.callback)
                finally:
                    self.tSerial.resume()
        finally:
            self.doneUpdate.emit(self.status)

    def terminate(self, timeout=1000):
        if not self.wait(timeout):
            print("[-] Terminate XMODEM Thread")
            QThread.terminate(self)
    def upload(self, port):
        import serial
        from xmodem import XMODEM
        import io
        # In case xmodem starts acting up
        # import logging
        # logging.basicConfig(level=logging.DEBUG)

        s = serial.Serial(port, 19200, timeout=1,
                          parity=serial.PARITY_NONE,
                          bytesize=8, stopbits=1,
                          xonxoff=0, rtscts=0)

        def getc(size, timeout=1):
            return s.read(size)

        def putc(data, timeout=1):
            return s.write(data)

        modem = XMODEM(getc, putc)
        modem.send(io.BytesIO(self.input_file))
Пример #43
0
def verify(ser, path, flashsize, bootloadersize, destructive=False):
    try:
        f = open(path, "rb")
    except IOError:
        CHK(False, "'%s': can't open file" % path, 5)
    data = f.read()

    f.close()
    modem = XMODEM(None, None)

    if destructive:
        ser.write("v")
        # no prefixed bytes, since uploading a bootloader
        bootloadersize = 0x0000
    else:
        ser.write("c")

    lines = []
    resp = ""
    while len(lines) < 3:
        resp += get_response(ser)
        lines = resp.split("\r\n")
    CHK(lines[1].startswith("CRC:"), RESP_ERR, 3)
    testcrc = lines[1][9:]

    crc = int(modem.calc_crc(data))
    # rest of the flash is 0xFF
    for i in xrange(flashsize - len(data) - bootloadersize):
        crc = modem.calc_crc("\xFF", crc)

    crc = hex(crc)[2:].upper()
    # extend to 4 chars
    crc = (4 - len(crc)) * "0" + crc
    print "CRC", crc, testcrc
    if testcrc == crc:
        INFO("Verify OK!")
    return testcrc == crc
Пример #44
0
class Client(threading.Thread):
    def __init__(self, io, server, filename):
        threading.Thread.__init__(self)
        self.io     = io
        self.server = server
        self.stream = open(filename, 'rb')

    def getc(self, data, timeout=0):
        return self.io.getc(data, 0)

    def putc(self, data, timeout=0):
        return self.io.putc(data, 0)

    def run(self):
        self.xmodem = XMODEM(self.getc, self.putc)
        print 'c.send', self.xmodem.send(self.stream)
Пример #45
0
class Protocol:

	def getc(self,size, timeout=1):		
		r = self.port.read()
		print("received:")
		a = array("B", r)
                print map(hex, a)		
		return r

	def putc(self,data, timeout=1):		
		self.port.write(data)
		
		return 1

	def __init__(self,portPath,mode='xmodem'): # (128bytes block). 'xmodem1k' for 1k block
		self.mode = mode
		self.modem = XMODEM(self.getc, self.putc,mode=self.mode)
		self.portPath=portPath

			
				
	def sendFile(self,filePath,callbackStatus):
		self.callbackStatus=callbackStatus
		try:
			self.port = serial.Serial(port=self.portPath,baudrate=115200,timeout = 10)
		except:
			return [False,"Invalid PORT"]
			
		r = False
		try:
			self.fileSize = os.path.getsize(filePath)
			stream = open(filePath, 'rb')			
			r = self.modem.send(stream,retry=2,callback=self.__callbackStatus)
		except:
			pass
		
		self.port.close()		
		return [r,"ERROR"];
	
	def __callbackStatus(self,total_packets, success_count, error_count):
		
		if(self.mode=="xmodem"):
			total = math.ceil(self.fileSize/128) + 1  # 128bytes block
		else:
			total = math.ceil(self.fileSize/1024) + 1 # 1k bytes block
		self.callbackStatus(total,success_count, error_count)
Пример #46
0
class Server(FakeIO, threading.Thread):
    def __init__(self, io):
        threading.Thread.__init__(self)
        self.io     = io
        self.stream = StringIO.StringIO()

    def getc(self, data, timeout=0):
        return self.io.getc(data, 1)

    def putc(self, data, timeout=0):
        return self.io.putc(data, 1)

    def run(self):
        self.xmodem = XMODEM(self.getc, self.putc)
        print 's.recv', self.xmodem.recv(self.stream)
        print 'got'
        print self.stream.getvalue()
Пример #47
0
        w,t,f = select.select([so], [], [], timeout)
        if w:
            data = so.read(size)
        else:
            data = None

        print 'getc(', repr(data), ')'
        return data

    def putc(data, timeout=3):
        w,t,f = select.select([], [si], [], timeout)
        if t:
            si.write(data)
            si.flush()
            size = len(data)
        else:
            size = None

        print 'putc(', repr(data), repr(size), ')'
        return size

    stream = StringIO.StringIO()
    xmodem = XMODEM(getc, putc)
    nbytes = xmodem.recv(stream, retry=8)

    print >> sys.stderr, 'received', nbytes, 'bytes'
    print >> sys.stderr, stream.getvalue()

    sys.exit(int(nbytes == 0))

Пример #48
0
    print "usage: %s tty bin" % sys.argv[0]
    sys.exit(1)


port = serial.Serial(port=portname, baudrate=115200)
if not port:
    print portname, 'not found'
    sys.exit(1)

stream = file(filename, 'rb')
if not stream:
    print filename, 'not found'
    sys.exit(1)

# problem was the timeout=0
#   needed to wait for NAK
def getc(size, timeout=1):
    return port.read(size)

def putc(data, timeout=1):
    port.write(data)

xmodem = XMODEM(getc, putc)

status = xmodem.send(stream)
print 'sent', status

stream.close()
sys.exit(int(not status))

Пример #49
0
        else:
            data = None

        print 'getc(', repr(data), ')'
        return data

    def putc(data, timeout=3):
        w,t,f = select.select([], [si], [], timeout)
        if t:
            si.write(data)
            si.flush()
            size = len(data)
        else:
            size = None

        print 'putc(', repr(data), repr(size), ')'
        return size

    stream = open(__file__, 'rb')
    xmodem = XMODEM(getc, putc)
    status = xmodem.send(stream, retry=8)
    stream.close()

    print >> sys.stderr, 'sent', status
    print >> sys.stderr, file(fn).read()

    os.unlink(fn)

    sys.exit(int(not status))

Пример #50
0
 def run(self):
     self.xmodem = XMODEM(self.getc, self.putc)
     print 's.recv', self.xmodem.recv(self.stream)
     print 'got'
     print self.stream.getvalue()
Пример #51
0
 def run(self):
     self.xmodem = XMODEM(self.getc, self.putc)
     print 'c.send', self.xmodem.send(self.stream)
Пример #52
0
class W7500_ISP_CMD(object):
    def __init__(self, comP, baud, parent, timeoutValue):
        self.ser = serial.Serial(comP, baud, timeout = timeoutValue)
        self.parent = parent

    def serialClose(self):
        self.ser.close()
    def __del__(self):
        self.serialClose()
        
    def negoComP(self):
        recv = ""
        #while True:
        for cnt in range(0,10):
            if recv == 0x00:
                continue
            elif recv == 'U':
                return 0;
            else:
                self.ser.write('U')
                recv = self.ser.read()
                for c in recv:
                    str = "Recv : {0:x}".format(ord(c))
                    print str
                    self.parent.m_statusBar_W7500_Status.SetStatusText(str)
                    #print "Recv : %04X" % ord(c)

                #time.sleep(0.2)
                print self.ser.readline()
                
        return -1
        
    def writeCmd(self,cmd,resp="0",paramLine=1,loopCnt=3):
        cmd = cmd + '\r'
        resp = resp + '\r\n'
        
        message = "Send Command : " + cmd
        print message
        #print "Send Command : %s" % cmd
        #self.parent.m_statusBar_W7500_Status.SetStatusText(message)

        self.ser.write(cmd)
        tempData =""
        
        for i in range(loopCnt):
            respData = self.ser.readline()
            if(i == paramLine -1):
                tempData = respData
            
            message = "Resp : " + respData
            print message
            #self.parent.m_statusBar_W7500_Status.SetStatusText(message)
            #print "Resp : %s" % respData,

            #if(respData[:1] == resp[:1]):
            if(respData == resp):
                break

        print("")
        return tempData

    def Dump(self,filename, addr,size,loopCnt=3, progressDialog=-1):
        cmd = "DUMP" + " " + addr + " " + size + '\r' 
        resp_val = []
        
        print "Send Command : %s" % cmd
        self.ser.write(cmd)
        
        f = open(filename,"wb")
        
        for i in range(loopCnt+1):
            respData = self.ser.readline()
            binary = binascii.a2b_hex(respData[9:17])
            progressDialog.Update(i)
            f.write(binary)

        f.close()
        
        respData = self.ser.readline()
        print respData
        
        return 0 

    
    def getc(self,size,timeout=1):
        return self.ser.read(size)
    def putc(self,data,timeout=1):
        return self.ser.write(data)
    
    def Xmodem_init(self):
        self.xmodem = XMODEM(self.getc,self.putc)
    def Xmodem_Send(self,start_addr,size,file_path,CallBack):
        cmd = "XPRG " + start_addr + " " + size + "\r"
        self.ser.write(cmd)
        stream = open(file_path,'rb')
        print "Start Send Binary using XMODEM"
        self.xmodem.send(stream,16,60,0,CallBack)
        stream.close()
 
        print self.ser.readall()
        print "End XMODEM"
Пример #53
0
	def __init__(self,portPath,mode='xmodem'): # (128bytes block). 'xmodem1k' for 1k block
		self.mode = mode
		self.modem = XMODEM(self.getc, self.putc,mode=self.mode)
		self.portPath=portPath
Пример #54
0
 def Xmodem_init(self):
     self.xmodem = XMODEM(self.getc,self.putc)
Пример #55
0
#xmodem module

txbyte=0

def getc(size, timeout=1):
	data = ser.read(size)
	return data

def putc(data, timeout=1):
	global txbyte

	ser.write(data)
	txbyte=txbyte+len(data)
	return len(data)

x = XMODEM(getc, putc)

while True:
	ser.flushInput()
	ser.write('#')
	rxchars = ser.read(3)
	print rxchars 
	if rxchars.find('>')>0:
		break

ser.flushInput()

cmdstring = "N#"
print "Send: [" + cmdstring + "]"
ser.write(cmdstring)
ser.read(2)