Пример #1
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))
Пример #2
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')
Пример #3
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?')
Пример #4
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
Пример #5
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
Пример #6
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)
Пример #7
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)
Пример #8
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
Пример #9
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)
Пример #10
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'")
Пример #11
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
Пример #12
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--")
Пример #13
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)
Пример #14
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
Пример #15
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)
Пример #16
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"))
Пример #17
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)
Пример #18
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'))
Пример #19
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'"
Пример #20
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()
Пример #21
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!")
Пример #22
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()
Пример #23
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
Пример #24
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")
Пример #25
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)
Пример #26
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)
    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))
Пример #28
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
Пример #29
0
def upgrade_ncp(ip, port, firmware_stream):

    s = socket.create_connection((ip, port))
    s.settimeout(5)
    s.send(OOB_HW_FLOW_OFF, socket.MSG_OOB)

    print("Entering upload mode...")

    s.send(b"1\n")  # Bootloader command to begin upload
    while s.recv(1) != b"\x00":
        pass

    print("Waiting for XMODEM...")
    while s.recv(1) != b"C":
        pass

    print("Uploading firmware...")

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

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

    modem = XMODEM(getc, putc)
    modem.send(firmware_stream)

    print("Upload complete. Starting new firmware...")
    s.send(b"2\n")  # Bootloader command to start new firmware

    s.sendall(OOB_HW_FLOW_ON, socket.MSG_OOB)

    s.close()

    print("Done")
Пример #30
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
Пример #31
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)
Пример #32
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
Пример #33
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('%s %s' % ('c.send', self.xmodem.send(self.stream)))
Пример #34
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)
Пример #35
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
Пример #36
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
Пример #37
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)
Пример #38
0
    def flash_and_close(self, file: bytes) -> bool:
        assert self.version.startswith("Gecko Bootloader"), self.version

        # STATIC FUNCTIONS
        def getc(size, timeout=1):
            read_data = self.read(size)
            return read_data

        def putc(data, timeout=1):
            self.write(data)
            time.sleep(0.001)

        # Enter '1' to initialize X-MODEM mode
        self.write(b"\x0A")
        self.write(b"1")

        # Wait for char 'C'
        success = False
        start_time = time.time()
        while time.time() - start_time < 10:
            if self.read() == b"C":
                success = True
                if time.time() - start_time > 5:
                    break
        if not success:
            return False

        from xmodem import XMODEM

        modem = XMODEM(getc, putc)
        modem.log = _LOGGER.getChild("xmodem")
        stream = io.BytesIO(file)
        if modem.send(stream):
            _LOGGER.info("Firmware upload complete")
        else:
            return False
        _LOGGER.info("Rebooting NCP...")

        self.close()  # better to close after flash
        time.sleep(4)

        return True
Пример #39
0
def upload(infile):
    global txbytes, txbytes2

    txbytes = 0
    txbytes2 = 0

    print("Starting upload")

    # Initiate xmodem download, wait for the initial NAK character
    exchangeCommand("ux", "\x15", atEnd=True)

    xm = XMODEM(getc, putc)
    print("Uploading", end="", flush=True)
    n = xm.send(infile, retry=10, timeout=1, quiet=False)
    print("")  # newline
    if n:
        print("Upload completed with success.")
    else:
        print("Upload error")
    return n
Пример #40
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"
Пример #41
0
    def __firm_update_one(self, id_485, firm_path):
        ret_desc = ""
        # 1. 发送ReadyUpdate
        ret = False
        cmd_bytes = bytes("ReadyUpdate\n", "utf-8")
        for i in range(5):
            ret, msg_detail = self.communicate(id_485,
                                               CMD_485_OTA,
                                               cmd_bytes,
                                               timeout=1)
            if ret and msg_detail.response == 0x21 and msg_detail.crc == 0xcb:
                ret = True
                break
        if not ret:
            ret_desc = "ReadyUpdate命令未收到响应"
        else:
            WorkerJzq.pro_rate_queue.put(
                (self.get_desc(id_485), PROGRESS_TYPE_FIRM, 10))
            # 2. 发送Update
            cmd_bytes = bytes("Update\n", "utf-8")
            ret, msg_ota = self.communicate(id_485,
                                            CMD_485_OTA,
                                            cmd_bytes,
                                            timeout=20)
            if not ret or msg_ota.response != 0x22 or msg_ota.crc != 0xcc:
                ret_desc = "Update命令未收到响应"
            else:
                WorkerJzq.pro_rate_queue.put(
                    (self.get_desc(id_485), PROGRESS_TYPE_FIRM, 20))
                # 3. XModem协议传输文件
                file = open(firm_path, "rb")
                file_size = os.path.getsize(firm_path)
                packet_num = math.ceil(file_size / WorkerJzq.packet_size)

                def getc(size, timeout=1):
                    # print("getc", end=" ")
                    r, m = self.get_msg485(id_485, CMD_485_OTA_XMODEM, timeout)
                    if r and len(m.data) == size:
                        # for b in m.data:
                        #     print("%c" % b, end="")
                        #     print("")
                        return m.data
                    else:
                        # print("")
                        return None

                def putc(data, timeout=1):
                    msg = MsgJZQSend(self.line_id)
                    msg.set_data(
                        Msg485Send(id_485).get_cmd(CMD_485_OTA_XMODEM, data))
                    self.recv_queue.queue.clear()
                    self.tcp_handler.send_queue.put(msg.get_bytes())
                    time.sleep(0.005)
                    return

                def callback_func(total_packets, success_count, error_count):
                    WorkerJzq.pro_rate_queue.put(
                        (self.get_desc(id_485), PROGRESS_TYPE_FIRM,
                         20 + int(success_count * 70 / packet_num)))

                try:
                    if WorkerJzq.packet_size == 128:
                        xmodem = XMODEM(getc, putc, mode='xmodem')
                    else:
                        xmodem = XMODEM(getc, putc, mode='xmodem1k')
                    xmodem_ret = xmodem.send(file,
                                             timeout=2,
                                             callback=callback_func)
                except Exception as e:
                    print(e)
                file.close()
                if not xmodem_ret:
                    ret_desc = "XModem传输错误"
                else:
                    # 4. 确认响应
                    ret, msg_ota = self.get_msg485(id_485, CMD_485_OTA, 15)
                    if not ret or msg_ota.response != 0x23 or msg_ota.crc != 0xcd:
                        ret_desc = "未收到固件更新完成响应"
                    else:
                        WorkerJzq.pro_rate_queue.put(
                            (self.get_desc(id_485), PROGRESS_TYPE_FIRM, 100))
        WorkerJzq.pro_ret_queue.put(
            (self.get_desc(id_485), PROGRESS_TYPE_FIRM, ret_desc))
Пример #42
0
class W7500_ISP(object):
    def __init__(self, comP, baud, timeoutValue):
        self.ser = serial.Serial(comP, baud, timeout=timeoutValue)

    def serialClose(self):
        self.ser.close()

    def __del__(self):
        self.serialClose()

    def negoComP(self):
        while True:
            try:
                self.ser.write(str.encode('U'))
                recv = self.ser.read()
                # print (recv.decode("utf-8"))

                if recv.decode("utf-8") == 'U':
                    print(
                        recv.decode("utf-8") +
                        self.ser.readline().decode("utf-8"))
                    print('Boot Mode Entered')

                    self.ser.write('\r'.encode('utf-8'))
                    time.sleep(1)
                    self.ser.read_all()
                    break
                else:
                    # print(recv)
                    print('.')
                time.sleep(1)
            except:
                pass

    def writeCmd(self, cmd, resp="0", paramLine=1, loopCnt=3, opt=0):
        cmd = cmd + '\r'
        resp = resp + '\r\n'

        print("Send Command : %s" % cmd)
        for i in cmd:
            self.ser.write(i.encode('utf-8'))
            time.sleep(0.01)
        # print(self.ser.write(cmd.encode('utf-8')))
        tempData = ""
        respData = ""

        for i in range(loopCnt):
            respData = self.ser.readline()
            respData = respData.decode("utf-8")
            if (i == paramLine - 1):
                tempData = respData

            print("Resp : %s" % (respData))
            if (respData == resp):
                print("Success")
                time.sleep(1)
                self.ser.read_all()
                break

        print("")
        return respData

    def unlockReadWrite(self):
        resp = self.writeCmd("LOCK PROG 00000000 00000000")
        return resp

    def eraseFlash(self):
        resp = self.writeCmd("ERAS MASS")
        return resp

    def eraseDataFlash(self, sector):
        if sector is '0':
            resp = self.writeCmd("ERAS DAT0")
        elif sector is '1':
            resp = self.writeCmd("ERAS DAT1")

        return resp

    def progDataFlash(self, sector):
        if sector is '0':
            resp = self.writeCmd("PROG DAT0 20000000")
            # resp = self.writeCmd("PROG DAT0")
        elif sector is '1':
            resp = self.writeCmd("PROG DAT1 20000100")
            # resp = self.writeCmd("PROG DAT1")

    def dumpData(self, flag):
        if flag is 'code':
            resp = self.writeCmd("DUMP 10000000 00020000",
                                 loopCnt=(1024 * 32 + 1))
        elif flag is 'data':
            resp = self.writeCmd("DUMP 1003FE00 00000200", loopCnt=129)
        elif flag is 'sram':
            resp = self.writeCmd("DUMP 20000000 00000200", loopCnt=129)
        return resp

    def downloadDatatoSRAM(self, filename):
        filesize = 0
        sentsize = 0
        with open(filename, 'rb') as f:
            read_data = f.read()
            filesize = len(read_data)
            print('filesize : %s' % str.format('{:08}', filesize))
            # send command
            self.writeCmd("DOWN 20000000 00000004", loopCnt=1)
            time.sleep(1)
            # if option is '0':
            #     tmp_data = read_data[0:256]
            # elif option is '1':
            #     tmp_data = read_data[256:512]

            bytemsg = ""
            for bytedata in range(4):
                # for bytedata in read_data:
                # hexadecimals = hex(bytedata)
                # print('%s, %s, %s' % (bytedata, hexadecimals, ''.join('%02X' % bytedata)))
                bytemsg = bytemsg + str.format('{:02X} ', bytedata)
                print('%s, %s' % (bytedata, bytemsg))

                sentsize = self.ser.write('a')
                print('%s sent' % (sentsize))
                # sentsize += self.ser.write(str.format('{:02X}', bytedata).encode('utf-8'))
                # print('%s, %s, %s, %s' % (bytedata, ord(bytedata), hex(ord(bytedata)), hex(ord(bytedata))[2:]))
            print('sentsize: %s' % sentsize)
            print(bytemsg)
            resp = self.ser.readline()
            resp = resp.decode('utf-8')
            print(resp)
            time.sleep(1)
            self.ser.read_all()
            self.ser.write('\r'.encode('utf-8'))
            self.ser.write('\r'.encode('utf-8'))
            # print('file size: %s' % filesize)
        f.closed

        return resp

        # hexadecimals = hex(size)
        # print(int(hexadecimals[2:]))
        # self.writeCmd("DOWN 20000000 " + str.format('{:08}', int(hexadecimals[2:])))
        # for i in range(size):
        #     self.ser.write('A'.encode('utf-8'))
        # resp = self.ser.readline()
        # resp = resp.decode('utf-8')
        # print(resp)

        # return resp

    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, filename, option):
        if option is 'code':
            cmd = "XPRG " + "10000000" + " " + "00020000" + "\r"
        elif option is 'sram':
            cmd = "XPRG " + "20000000" + " " + "00000200" + "\r"
        print(cmd)
        self.ser.write(cmd.encode('utf-8'))
        print("Start Send Binary using XMODEM")
        stream = open(filename, 'rb')
        print(self.xmodem.send(stream))
        stream.close()

        print(self.ser.readall())
        print("End XMODEM")

    def downloadDataByXModem(self, filename, option):
        self.Xmodem_init()
        self.Xmodem_Send(filename, option)

    def resetSystem(self):
        self.ser.write("REST\r".encode('utf-8'))
        resp = self.ser.readline()
        print(resp)
        return resp

    def readSerial(self):
        return self.ser.read_all()
Пример #43
0
    sys.stdout.write(c)

    if c == '>':
        print "Ricevuto '>'"
        break

print "Inizio programmazione serial flash"

address = 0x200000
cmdstring = "S%06X,#" % (address)
print "  Send: [" + cmdstring + "]"
ser.flushInput()
ser.write(cmdstring)

stream = open(filename + "_patched", 'rb')
x.send(stream)
stream.close()

while ser.read(1) != '>':
    time.sleep(0.1)

macUpdate(filename)

cmdstring = "G200000#"
print "  Send: [" + cmdstring + "]"
ser.write(cmdstring)

print "Fine programmazione flash"

token = ""
while True:
Пример #44
0
        ch = port.read(size)
        # echo 'x' to report failure if read timed out/failed
        if ch == b'':  # received no bytes
            if not success: printq('x', end='')
            return None
        return ch

    def putc(data, timeout=1):
        n = port.write(data)
        # echo '.' to report full packet successfully sent
        if n >= 128:
            printq('.', end='')

    try:
        xmodem = XMODEM(getc, putc)
        success = xmodem.send(stream, retry=5)
        if not success:
            error(
                "Send failed (bootloader not listening?)", """
I waited a few seconds for an acknowledgement from the bootloader
and didn't hear anything. Do you need to reset your Pi?

Further help at http://cs107e.github.io/guides/bootloader/#troubleshooting
""")
    except serial.serialutil.SerialException as ex:
        error(str(ex))
    except KeyboardInterrupt:
        error(
            "Canceled by user pressing Ctrl-C.", """
You should probably restart the Pi, since you interrupted it mid-load.
""")
Пример #45
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))

Пример #46
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))

Пример #47
0
		break

ser.flushInput()

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

cmdstring = "S300000,#"
print "Send: [" + cmdstring + "]"
ser.write(cmdstring)

print "Send file %s in XModem" % filename
stream = open(filename, 'rb')
x.send(stream)
stream.close()

print "txbyte=%d" % txbyte

cmdstring = "G300000#"
print "Send: [" + cmdstring + "]"
ser.write(cmdstring)

print "Characters received from the Aria module (type Ctrl-C to exit)"

while True:
    s = ser.read(1) 
    sys.stdout.write(s)

ser.close()