有很多方法可以做到这一点,仅举几例:
- 从 Raspi 向 PC 发送 UDP 消息
- 从 Raspi 向 PC 发送 TCP 流
- 将读数放入Redis并允许您网络上的任何人收集它们 - 例如这里
- 使用 MQTT 客户端从您的 Raspi 发布读数,并在您的 PC 作为服务器上订阅该主题
- 在一台机器上运行 Python多处理管理器并从另一台机器连接 - 请参阅此处的“使用远程管理器”
- 通过蓝牙发送读数
这是上面使用 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()
这里有一个蓝牙通信的例子。