简体   繁体   English

如何将串行输入拆分为消息

[英]How to split serial input into messages

I have 2 serial ports on Raspberry Pi.我在 Raspberry Pi 上有 2 个串行端口。 Currently, the code is reading data from port 1 and writing it on port 2 and vice versa.目前,代码正在从端口 1 读取数据并将其写入端口 2,反之亦然。 What I am trying to do is split the input that I am reading from both ports and split it into different messages (group of character) based on a specified character (for example # or !)我要做的是拆分我从两个端口读取的输入,并根据指定的字符(例如 # 或!)将其拆分为不同的消息(字符组)

Also, how can I modify the current 'for' loop in the end so that I can split the messages for both ports, currently the code is only written to split data from 1 port.另外,最后如何修改当前的“for”循环,以便我可以拆分两个端口的消息,目前代码仅用于从 1 个端口拆分数据。

I have already tried split() and it gives a type error.我已经尝试过 split() 并且它给出了类型错误。 The reason can be serial input might be in a different type原因可能是串行输入可能是不同的类型

import serial
ser1 = serial.Serial('/dev/ttyUSB0', timeout=2)
ser2 = serial.Serial('/dev/ttyUSB1', timeout=2)
print (ser1)
print (ser2)
ser1_list = []
ser2_list = []

while (True):
    data1 = ser1.readlines()
    data2 = ser2.readlines()
    if data1 or data2:
        ser1_list.extend(data1)
        ser2.writelines(data1)
        byte_split1 = ser1_list.split("1")
        ser2_list.extend(data2)
        ser1.writelines(data2)
        byte_split2 = ser1.split('1')
        for x in byte_split1:
            print(x)
    else:
        break
ser1.close()
ser2.close()

Example for the expected result: If the input is:预期结果的示例:如果输入是:

abcde#fghi#jklmnop#

it would output:它将 output:

abcde
fghi
jklmnop

It appears that you're trying to set up something like a chat between the two locations.您似乎正在尝试在两个位置之间设置类似聊天的内容。 Please consider looking up how to do that in canonical fashion:请考虑以规范的方式查找如何做到这一点:

Split this into parallel processes, one each for ser1 => ser2 and the other for ser2 => ser1 .将其拆分为并行进程,一个用于ser1 => ser2 ,另一个用于ser2 => ser1 Each process will handle communication in its own direction.每个进程都将按照自己的方向处理通信。

This allows you to write one listener for each port;这允许您为每个端口编写一个侦听器; your two processes will be identical, except that you instantiate them with the ports in opposite order.您的两个进程将是相同的,只是您以相反的顺序使用端口实例化它们。 Each listener gathers traffic until it gets to a separator;每个侦听器都会收集流量,直到到达分隔符; at that point, it writes the buffer contents up to that point and moves the buffer pointer.此时,它将缓冲区内容写入该点并移动缓冲区指针。 There are plenty of I/O packages to do this for you;有很多 I/O 包可以为您做到这一点; you're merely "chunking" the stream with that separator character.你只是用那个分隔符“分块” stream 。

That should be enough guidance and references for you to find the examples you need.这应该足以让您找到所需的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM