明日の自分のために

主に自分用のメモなど

シリアル通信のシミュレート方法

Raspberry Piでシリアル通信を行うプログラムを作成しているときに、socatを使ってお手軽に動作確認をする方法のメモ。

Socat

Manからの引用。シリアルだけじゃなくてソケットなどいろいろ使える。

Socat is a command line based utility that establishes two bidirectional byte streams and transfers data between them. Because the streams can be constructed from a large set of different types of data sinks and sources (see address types), and because lots of address options may be applied to the streams, socat can be used for many different purposes.

使ってみる

/tmp/ttyV0と/tmp/ttyV1という仮想のシリアルデバイスを作成してこの2つでシリアル通信を行う。コマンドは以下の通り。 もし権限がないと怒られる場合はchmod 666 /tmp/ttyV0などしてあげればいい。

pi@raspberrypi:~ $ socat -d -d pty,raw,echo=0,link=/tmp/ttyV0, pty,raw,echo=0,link=/tmp/ttyV1
2018/08/13 07:55:26 socat[519] N PTY is /dev/pts/2
2018/08/13 07:55:26 socat[519] N PTY is /dev/pts/3
2018/08/13 07:55:26 socat[519] N starting data transfer loop with FDs [5,5] and [7,7]

RaspberryPi上のプログラムから利用したり、echo "hello" > /tmp/ttyV1などとしてみればそのままシリアルでメッセージのやり取りができる。

参考

https://ubuntuforums.org/showthread.php?t=2258621