【问题标题】:Send binary file over serial with pyserial and python 3.4使用 pyserial 和 python 3.4 通过串行发送二进制文件
【发布时间】:2017-08-22 06:28:06
【问题描述】:

我正在尝试使用 python 通过 Windows 中的串行 COM 端口发送二进制文件,然后将相同的流写入文件。本质上,我正在尝试制作文件的副本,但由于这不是我的最终目标,我不想使用 shutil 或其他复制功能。我有一个打算通过 COM 端口发送文件的脚本,以及一个充当侦听器和文件编写器的脚本。发件人脚本似乎可以毫无问题地将文件作为二进制文件发送,但我在使用监听器脚本时遇到了问题,特别是让它正确输出文件。我在下面发布了我的脚本。我从“发送者”发送的二进制流是否正确,如何更改“侦听器”以正确写入文件?

听众:

from serial import Serial

def bytes_from_file(filename, chunksize=8192):
    with open(filename, "rb") as f:
        while True:
            chunk = f.read(chunksize)
            if chunk:
                for b in chunk:
                    yield b
            else:
                break

def sendfile():
    ser = Serial("COM5", 115200, timeout=30, writeTimeout=0)
    filename = "c:\\temp\\savetestfile.txt"
    # wait for the "Sendfile" command over serial
    h = b''
    while h == b'':
        h = ser.read(ser.inWaiting())
    h = h.decode("utf-8")

    #respond with "y" if "sendfile" recieved to start data stream
    if h == "sendfile":
        ser.write(b'y')
    with open(filename, "wb") as f:
        while True:
            b=ser.read(1)
            print (b)
            if b: 
                n=f.write(b)
            else: break

if __name__ =="__main__":

    sendfile()

发件人:

from serial import Serial 

def bytes_from_file(filename, chunksize=8192):
    with open(filename, "rb") as f:
        while True:
            chunk = f.read(chunksize)
            if chunk:
                for b in chunk:
                    yield b
            else:
                break


def sendfile():
    #com = getCOMPortInfo()
    ser = Serial("COM2", 115200, timeout=10, writeTimeout=0)
    filename = askopenfilename(title="Stuff", initialdir="C:\\")
    #if filename is "":
    #   exit()
    ser.write(b"sendfile")
    ok = ""
    #while True:te

    h = ser.read()
    ok = ok + h.decode("utf-8")
    if ok is "y":
        print("yes!")
        for b in bytes_from_file(filename):
            #b = str(b).encode()
            print(b)
            ser.write(b)
    else:
        print ("Failure")
    ser.close()



# example:

if __name__ =="__main__":


    print(sendfile())

【问题讨论】:

  • 对于仍然遇到这个问题的任何人,我从来没有找到一个好的答案。如果您在旅行中遇到一个,请随时提出建议。我最终重新设计了我的设计,以便不需要发送文件,但如果可能的话,我仍然想知道如何去做。

标签: python file binary pyserial transfer


【解决方案1】:

我将二进制文件翻译成\xYY 格式,并使用“printf”命令将级联字符串写入目标文件。它引入了开销,但由于我正在处理小文件,所以没关系。

content = f.read().hex()
content = "".join(["\\x" + content[x:x + 2] for x in range(0, len(content), 2)])
write_cmds.append("printf \"" + tx_str + "\" >> " + target_file_name + "\r\n")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    相关资源
    最近更新 更多