Skip to main content
 首页 » 编程设计

python之在 Raspberry 上使用 Python 进行传感器监控

2024年12月31日12zhenyulu

我需要一些帮助来找到编写 Raspberry python 程序的最佳方法。

在这个程序中,我需要监控来自连接到树莓派的各种传感器的多个值,并通过 pyqt GUI 与这些值进行交互。 GUI 和传感器驱动程序必须完全分开。

为此,我考虑在 GUI 和传感器之间制作并使用“变量管理器”对象,作为“缓冲区”或类似的东西。通过使用线程和锁,传感器会不断更新变量管理器(在相应的驱动程序中使用 while 循环),而 GUI 会在我需要时查询某些值。

如果能够从 gui 向传感器发送一些命令也很好,但我不知道如何在此配置中执行此操作。

您认为这可以正常工作吗?有没有其他更有效/更适合这样做的方法?

非常感谢您!

请您参考如下方法:

我会这样做:

[物理传感器] --> [Python 传感器监视器] --> [PubNub/类似]

# Not tested, probably not good 
from threading import Thread 
from pubnub import PubNub 
 
class SensorMonitor(threading.Thread): 
  def __init__(self): 
    self.pubnub = PubNub("demo", "demo") 
    self.switch = True 
 
  def _on_receive(self, sensor_data): 
    # can also do async() with a callback - https://www.pubnub.com/docs/python/data-streams-publish-and-subscribe 
    self.pubnub.publish().channel('raw_data').message(sensor_data).sync() 
 
  @staticmethod 
  def _poll_sensor(address): 
    data = get_sensor_data(address) 
    return data 
 
  def run(self): 
    while self.switch: 
      _data = poll_sensor('my_address') 
      self._on_receive(_data) 
      time.sleep(1) 
 
  def terminate(self): 
    self.switch = False 
 
monitor = SensorMonitor() 
monitor.start() 

然后您的 GUI 可以使用 PubNub 消费者在流式传输和检查/执行操作时获取数据。你可以在这里使用 JS 或 Python!