有很多方法可以做到这一点,仅举几例:
- 将 UDP 消息从 Raspi 发送到 PC
- 将 TCP 流从 Raspi 发送到 PC
- 将读数放入Redis并允许您网络上的任何人收集它们 - 例如here https://stackoverflow.com/a/58521903/2836621
- 使用 MQTT 客户端发布来自 Raspi 的读数,并在作为服务器的 PC 上订阅该主题
- 运行Python多处理管理器在一台机器上并从另一台机器连接 - 请参阅“使用远程管理器” here https://docs.python.org/3/library/multiprocessing.html#managers
- 通过蓝牙发送读数
这是上面第一个建议使用 UDP 的可能实现。首先,Raspi端生成3个读数X、Y和Z,并通过UDP每秒将它们发送到PC:
#!/usr/bin/env python3
import socket
import sys
from time import sleep
import random
from struct import pack
# Create a UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
host, port = '192.168.0.8', 65000
server_address = (host, port)
# Generate some random start values
x, y, z = random.random(), random.random(), random.random()
# Send a few messages
for i in range(10):
# Pack three 32-bit floats into message and send
message = pack('3f', x, y, z)
sock.sendto(message, server_address)
sleep(1)
x += 1
y += 1
z += 1
PC端的匹配代码如下:
#!/usr/bin/env python3
import socket
import sys
from struct import unpack
# Create a UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind the socket to the port
host, port = '0.0.0.0', 65000
server_address = (host, port)
print(f'Starting UDP server on {host} port {port}')
sock.bind(server_address)
while True:
# Wait for message
message, address = sock.recvfrom(4096)
print(f'Received {len(message)} bytes:')
x, y, z = unpack('3f', message)
print(f'X: {x}, Y: {y}, Z: {z}')
这是 MQTT 建议的可能实现。首先,发布者发布三个值。请注意,我有mosquitto
在我的桌面上运行的代理:
#!/usr/bin/env python3
from time import sleep
import random
import paho.mqtt.client as mqtt
broker = '192.168.0.8'
client = mqtt.Client()
client.connect(broker,1883,60)
# Generate some random start values
x, y, z = random.random(), random.random(), random.random()
# Send a few messages
for i in range(10):
# Publish out three values
client.publish("topic/XYZ", f'{x},{y},{z}');
sleep(1)
x += 1
y += 1
z += 1
这是订阅者,它监听消息并打印它们:
#!/usr/bin/env python3
import socket
import sys
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("topic/XYZ")
def on_message(client, userdata, msg):
message = msg.payload.decode()
print(f'Message received: {message}')
broker = '192.168.0.8'
client = mqtt.Client()
client.connect(broker,1883,60)
client.on_connect = on_connect
client.on_message = on_message
client.loop_forever()
有一个蓝牙通信的例子here https://stackoverflow.com/a/70439467/2836621.
有一个类似的答案,还有更多例子here https://stackoverflow.com/a/76377651/2836621.