如何确保3 Raspberry Pi之间的并行通信?

时间:2017-08-02 08:52:54

标签: python-3.x raspberry-pi

我尝试与3 Raspberry Pi进行通信:一个是服务器,另一个是客户端。服务器同时接收和发送信息给两个客户端。我正在寻找一种确保沟通的方法。请帮忙! PS:我使用的是Python3

3 个答案:

答案 0 :(得分:3)

对于那种事情,MQTT可能会很好用,但你的问题很模糊。

有可用的Python库,但您可以在命令行中在终端中进行测试:

安装时:

sudo wget http://repo.mosquitto.org/debian/mosquitto-repo.gpg.key
sudo apt-key add mosquitto-repo.gpg.key
cd /etc/apt/sources.list.d/
sudo wget http://repo.mosquitto.org/debian/mosquitto-jessie.list
sudo apt-get update
sudo apt-get install mosquitto mosquitto-clients python-mosquitto

首先以详细模式运行服务器(消息代理),以便我们可以看到发生了什么:

mosquitto -v

现在,在一个新的终端中,运行一个用户来监听" debug"流:

mosquitto_sub -h localhost -t debug

现在,在另一个新的终端中,运行一个发送到" debug"流:

mosquitto_pub -h 127.0.0.1 -t debug -m "Hello"

显然更改IP地址以匹配您的设置,上面是一台机器上的一个非常简单的示例。

因此,具体而言,您的服务器可能对其两个客户端的状态感兴趣,因此它将订阅两个通道,即client0statusclient1status,而client0将在通道{{1 }和client1将在频道client0status上发布。

关于命令,client0将订阅通道client1status以接收命令,而client1将订阅通道client0cmd,而服务器将在这两个通道上发布命令。

这是一个有关此类设置工作的小视频。左上角的窗口正在运行mosquitto服务器。右上方窗口订阅了两个Raspberry Pis的状态通道 - 这可能与服务器位于同一台机器上。左下角的窗口是第一个Raspberry Pi,右下角的窗口是第二个Raspberry Pi:

enter image description here

答案 1 :(得分:1)

如果您想要并行通信,可以考虑使用websocket。 请参阅:https://pypi.python.org/pypi/websockets

但是HTTP和TCP也是一个选项,它取决于你的用例......

答案 2 :(得分:0)

Another option might be to install Redis on your Raspberry Pis. It is a very fast "data structure server" - meaning you can use it to implement hashes, sets, queues etc.

You can install it on your Raspberry Pi with:

sudo apt-get install redis-server

If you want to use it among multiple Raspberry Pis, you need to comment out the line in the config file that binds to the local host only, so that it looks like this in /etc/redis/redis.conf and then restart it:

#bind 127.0.0.1

Then, you can test the server from any of your Raspberry Pis with the ping command it should respond with a PONG:

redis-cli -h <SERVER> ping
PONG

Now, on your pi0 client, you can do a blocking wait (BLPOP) on the pi0cmd queue to wait for a command:

redis-cli -h <SERVER> <<< "blpop pi0cmd 0"

and that will wait till your server sends a command on the pi0cmd queue:

redis-cli -h <SERVER> <<< "lpush pi0cmd 000"

So, those commands are implemented in a queue in the Redis data structure server.

You could implement the status in a simple string data structure. So the client updates his status in pi0status with:

redis-cli -h <SERVER> <<< "set pi0status HAPPY"

and the server can get the status at any time with:

redis-cli <<< "get pi0status"
"HAPPY"

Here is a little animation of it working as above:

enter image description here

All the Redis commands are listed here.

Again, there are Python versions of this.