开发者

use python twisted framework to connect to multiple serial sockets

I currently use twisted to connect to a serial device I have, using code like the following.

from twisted.i开发者_Go百科nternet import reactor
SerialPort(Handler(), "/dev/ttyACM1", reactor, baudrate='9600')
reactor.run()

However, I know need to extend the application to monitor for new serial devices being added (and removed). I currently use pyinotify to look for new devices being added/removed, and this seems to work well.

class EventHandler(pyinotify.ProcessEvent):
    def process_IN_CREATE(self, event):
        ... connect to serial device
        ...

At the moment I seem to have several problems. The biggest I think is that I just don't know enough about Twisted to know what the 'correct' way of doing this is.

Currently as I have it, the pyinotify event handler kicks of in a separate thread, meaning the reactor is not running in the main thread. Is this an issue?

Once the first device is connected, I struggle to add a second - not least the reactor is already running by the time the second device is added. Even if I protect that with a

if not reactor.running: 

the second connection doesn't add to the reactor properly (at least connectionMade, dataReceived received methods don't fire).

If I start the reactor first, then let the pyinotify events try and add to the running reactor this doesn't seem to work either - the device does connect, but the dataReceived method never gets called.

Basically, I'm sure there is a neat recipe for getting this to work, I just haven't been able to find it, either through Google or trial and error. Can anybody suggest to me how I might be able to get this working?

Thanks in advance for any help you're able to offer,

Simon


Any time you want to use a Twisted API but your code isn't running in the same thread as the reactor, you can use reactor.callFromThread to have the reactor call some of your code in its thread. So, for example, you could do something like this:

def process_IN_CREATE(self, event):
    reactor.callFromThread(
        SerialPort, Handler(), "/dev/ttyACM1", reactor, baudrate='9600')

However, you also don't need to have any extra threads to do what you described. Instead of using pyinotify, use twisted.internet.inotify:

from twisted.python.filepath import FilePath
from twisted.internet.inotify import IN_CREATE, INotify
from twisted.internet import reactor

def created(ignored, path, mask):
    SerialPort(
        Handler(),
        "/dev/ttyACM1", # Or... use `path` here?
        reactor, baudrate='9600')

notifier = INotify()
notifier.watch(FilePath("/some/directory"), IN_CREATE, callbacks=[created])
notifier.startReading()

reactor.run()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜