Raspberry Pi(Debian)上的Twisted Python脚本通过USB与Arduino进行通信

时间:2013-07-19 07:03:21

标签: python serial-port arduino twisted

我一直致力于Arduino / Raspberry Pi项目,我发现自己不仅学习Python而且学习Twisted Python;所以我提前为我的新闻道歉。我现在试图保持简单,只是尝试在两个设备之间的任何时间发送一个字符。

到目前为止,我能够从Raspberry Pi发送到Arduino并有效地关闭/打开LED,就像预期的那样。但是,我似乎无法生成Twisted代码,它将检测从Arduino到串行端口上的RPi的任何内容。我验证了Arduino在RPi上运行的Arduino程序员中使用串行监视器应用程序每2秒发送一次字符。

下面的代码在RPi上运行,接收GET请求并通过串口将一些数据传递给Arduino。我似乎无法使用此代码来侦听相同的串行端口。 :/我一直在研究这个问题已经有一个多月了,似乎被卡住了。我似乎无法找到Twisted Python在线接收串行数据的好例子;或者至少是我理解的一个例子。无论如何,这是我到目前为止:

import sys
from urlparse import urlparse
from twisted.web import server, resource
from twisted.internet import reactor
from twisted.internet.protocol import Factory, Protocol
from twisted.internet.serialport import SerialPort

serServ = None

class USBclient(Protocol):
    def connectionMade(self):
        global serServ
        serServ = self
        print 'Arduino device: ', serServ, ' is connected.'

    def cmdReceived(self, cmd):
        serServ.transport.write(cmd)
        print cmd, ' - sent to Arduino.'
        pass

    def serialReadEvent(self):      #maybe it should be: doRead()? Couldn't get either to work.
        print 'data from arduino is at the serial port!'

class HTTPserver(resource.Resource):
    isLeaf = True
    def render_GET(self, request):      #passes the data from the get request
        print 'HTTP request received'
        myArduino = USBclient()
        stringit = str(request)
        parse = stringit.split()
        command, path, version = parse
        myArduino.cmdReceived(path)

class cmdTransport(Protocol):
    def __init__(self, factory):
        self.factory = factory

class cmdTransportFactory(Factory):
    protocol = cmdTransport

if __name__ == '__main__':
    HTTPsetup = server.Site(HTTPserver())
    reactor.listenTCP(5000, HTTPsetup)
    SerialPort(USBclient(), '/dev/ttyACM0', reactor, baudrate='115200')
    reactor.run()

正如你所看到的,代码只是在串口寻找任何东西,但我似乎无法让这种魔力发生。在此先感谢,任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:2)

从此判断:http://twistedmatrix.com/trac/browser/tags/releases/twisted-12.3.0/twisted/internet/_win32serialport.py#L84您应该查看Protocol子类的dataReceived(self,...)方法

因此:

class USBclient(Protocol):
    def connectionMade(self):
        global serServ
        serServ = self
        print 'Arduino device: ', serServ, ' is connected.'

    def cmdReceived(self, cmd):
        serServ.transport.write(cmd)
        print cmd, ' - sent to Arduino.'
        pass

    def dataReceived(self,data):      
        print 'USBclient.dataReceived called with:'
        print str(data)

试试看它是否有效。