2012-03-24 44 views
2

我有一個Arduino板連接到我的PC的串行端口。主板將數據發送到PC,但它也可以通過同一個通道接收命令。但是,發送的數據和訂單之間沒有關係或順序。如何在同一個Python程序中偵聽HTTP請求和串行通道?

在PC中,我創建了一個監聽串口的守護進程。爲了將數據發送到Arduino,我想在守護進程中建立一個XML RPC服務器。問題是我不知道如何在同一個程序中聽串行端口並參加XML RPC請求。

最初,我曾在我的腦海裏是這樣的:

while true 
    if there is incoming data in the serial channel 
     blah blah 

    if there are HTTP requests 
     start attending the XML RPC request 

我一直在尋找(SimpleXMLRPCServer,它web.py)的聽力和處理請求所有的時間服務器。我想告訴我的XML RPC服務器「等待,如果沒有請求我們要檢查串行通道​​」。

我該如何做到這一點或類似的東西?還是應該改變我的設計?如果我在另一個進程中使用XML RPC服務器,我想我需要某種進程間通信,這就是爲什麼我首先使用XML RPC的原因。

回答

0

您可以使用所謂的程序與線程。它允許並行執行多個操作。

如果您使用Python,你在這裏更多的信息:http://docs.python.org/library/threading.html#thread-objects

但是線程可能很難graps和正確使用。有幾個關於線程化Python的教程,不要猶豫,用搜索引擎來檢查它們。

最大的想法是做這樣的事情:

import threading 

def processCommands(): 
    while True: 
     #wait and process commands 

def readSerial(): 
    while True: 
     #read serial 

serialThread = threading.Thread(target=readSerial) 
commandThread = threading.Thread(target=processCommands) 
serialThread.start() 
commandThread.start() 

#Wait for the command thread to exit, 
#otherwise the programs would immediately exit 
commandThread.join() 
+0

我用這個方法,因爲它是更普遍的。因爲我已經聽到了很多關於它的好消息,所以下次我會給它一個扭曲的答案。如果你感興趣的代碼是在這裏:[vr-domotic](https://sourceforge.net/projects/vr-domotic/) – Camotito 2012-11-21 15:35:47

2

另一個(可能更好)的方法是應用程序遷移到異步I/O。例如,您可以使用雙絞線框架(如Twisted)在兩個單獨的協議處理程序中異步同時處理HTTP和串行通信。

類似的東西:

from twisted.web import server, resource 
from twisted.internet import protocol, reactor 
from twisted.internet.serialport import SerialPort 

class Echo(protocol.Protocol): 
    def dataReceived(self, data): 
     self.transport.write(data) 

class HttpResource(resource.Resource): 
    isLeaf = True 

    def render_GET(self, request): 
     request.setHeader("content-type", "text/plain") 
     return "Hello there\n" 

reactor.listenTCP(8080, server.Site(HttpResource())) 
SerialPort(Echo(), <your serial port>, reactor, baudrate=9600) 

reactor.run() 
+0

+1爲Twisted,這顯然是一個爲此目的而創建的框架 – Krumelur 2012-03-24 10:38:59

相關問題