XMODEM for python

夙愿已清 提交于 2019-12-06 06:29:30
def xmodem_send(serial, file):
t, anim = 0, '|/-\\'
serial.setTimeout(1)
while 1:
    if serial.read(1) != NAK:
        t = t + 1
        print anim[t%len(anim)],'\r',
        if t == 60 : return False
    else:
        break

p = 1
s = file.read(128)
while s:
    s = s + '\xFF'*(128 - len(s))
    chk = 0
    for c in s:
        chk+=ord(c)
    while 1:
        serial.write(SOH)
        serial.write(chr(p))
        serial.write(chr(255 - p))
        serial.write(s)
        serial.write(chr(chk%256))
        serial.flush()

        answer = serial.read(1)
        if  answer == NAK: continue
        if  answer == ACK: break
        return False
    s = file.read(128)
    p = (p + 1)%256
    print '.',
serial.write(EOT)
return True

There is XMODEM module on PyPi. It handles both sending and receiving of data with XModem. Below is sample of its usage:

import serial
try:
    from cStringIO import StringIO
except:
    from StringIO import StringIO
from xmodem import XMODEM, NAK
from time import sleep

def readUntil(char = None):
    def serialPortReader():
        while True:
            tmp = port.read(1)
            if not tmp or (char and char == tmp):
                break
            yield tmp
    return ''.join(serialPortReader())

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

def putc(data, timeout=1):
    port.write(data)
    sleep(0.001) # give device time to prepare new buffer and start sending it

port = serial.Serial(port='COM5',parity=serial.PARITY_NONE,bytesize=serial.EIGHTBITS,stopbits=serial.STOPBITS_ONE,timeout=0,xonxoff=0,rtscts=0,dsrdtr=0,baudrate=115200)
port.write("command that initiates xmodem send from device\r\n")
sleep(0.02) # give device time to handle command and start sending response
readUntil(NAK)
buffer = StringIO()
XMODEM(getc, putc).recv(buffer, crc_mode = 0, quiet = 1)
contents = buffer.getvalue()
buffer.close()
readUntil()

I think you’re stuck with rolling your own.

You might be able to use sz, which implements X/Y/ZMODEM. You could call out to the binary, or port the necessary code to Python.

Here is a link to XMODEM documentation that will be useful if you have to write your own. It has detailed description of the original XMODEM, XMODEM-CRC and XMODEM-1K.

You might also find this c-code of interest.

You can try using SWIG to create Python bindings for the C libraries linked above (or any other C/C++ libraries you find online). That will allow you to use the same C API directly from Python.

The actual implementation will of course still be in C/C++, since SWIG merely creates bindings to the functions of interest.

There is a python module that you can use -> https://pypi.python.org/pypi/xmodem

You can see the transfer protocol in http://pythonhosted.org//xmodem/xmodem.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!