维护硬件设备远程服务连接的最佳方法?

时间:2014-03-31 15:13:24

标签: websocket raspberry-pi

这是一个尴尬的问题,但是这里有。

我正在尝试使用Raspberry Pi构建一个门解锁系统。我希望Pi保持与远程服务器的开放连接,这样我就可以测试存在(即Pi是否活着),并发送命令。我还希望减轻典型的家用路由器NAT&动态IP问题。

我的问题是:什么协议最适合这个?

我在想的是使用类似网络套接字的东西,这样我就可以连接到像Pusher这样的服务或我自己的服务器。这个问题是我将从直接的Python中做到这一点,因此中间没有Web浏览器。我不知道我有什么其他选择,如果有的话。

对这个问题的开放式性质表示歉意,但我不确定还能在哪里问。

1 个答案:

答案 0 :(得分:5)

实时网络是在Raspberry Pi和远程服务器(或任意数量的远程设备)之间传输数据的绝佳媒介。我听了Gordon Hollingwortha talk at API Strategy Conference about his educational strategy with the Raspberry Pi,我从那以后一直在玩一个。这就是我所学到的。

首先,由于Pi运行 linux ,您可以使用您喜欢的任何语言进行编码。我最熟悉的实时网络 PubNub SDKs in something like 50 languages。特别是,使用PubNub Python SDK,您可以使用此代码块订阅事件:

pubnub = Pubnub(
    "demo",  ## PUBLISH_KEY
    "demo",  ## SUBSCRIBE_KEY
    None,    ## SECRET_KEY
    False    ## SSL_ON?
)

def receive(message) :
    print(message)
    return True

pubnub.subscribe({
    'channel'  : 'hello_world',
    'callback' : receive 
})

要发送消息,既然您已经定义了pubnub变量,那么您只需使用:

info = pubnub.publish({
    'channel' : 'hello_world',
    'message' : {
        'some_text' : 'Hello my World'
    }
})
print(info)

此SDK非常轻量级且易于实现(PubNub为free for up to 1m messages per month。)

由于您询问了不同的协议,我不妨提一下,如果您想使用更低级别的服务,您可以发送 TCP数据包 directly to the PubNub interface using the instructions in this gist。简言之,将

telnet pubsub.pubnub.com 80

GET /stream/demo/a/0/10000 HTTP/1.1
Host: pubsub.pubnub.com

与使用SDK或WebSocket解决方案相比,这显然有助于降低功耗。

另一方面,由于您熟悉Python和WebSockets,因此您始终可以推出自己的解决方案。 Heroku有a post about spinning up a chat server using Python WebSockets on their blog使用异步回调和 Redis 。以下是将消息联合到不同客户端的代码示例:

def run(self):
    """Listens for new messages in Redis, and sends them to clients."""
    for data in self.__iter_data():
        for client in self.clients:
            gevent.spawn(self.send, client, data)
祝你好运,让我知道它是怎么回事!