topikachu / python-ev3

a project to run lego ev3 in python
Apache License 2.0
189 stars 73 forks source link

Asynchronous API #33

Open pepijndevos opened 9 years ago

pepijndevos commented 9 years ago

The kernel interface is very much asynchronous. You write a value, and stuff happens. Currently, when you want to wait for a sensor or motor, you have to poll it.

I'm currently using this snippet in my code, but maybe we should think about a proper API, possibly using asyncio, Twisted, Gevent, or something else.

from ev3 import lego, ev3dev
import time
import select
import os

p = select.poll()
callbacks = {}

def poll(timeout):
    for fd, mask in p.poll(timeout):
        os.lseek(fd, 0, os.SEEK_SET)
        state = os.read(fd, 16)
        if state == "idle\n":
            p.unregister(fd)
            os.close(fd)
            callbacks.pop(fd)()

def on_completion(motor, callback):
    fd = os.open(motor.sys_path + '/state', os.O_RDONLY)
    callbacks[fd] = callback
    os.read(fd, 16)
    p.register(fd, select.POLLPRI)
topikachu commented 9 years ago

Well, an event based system is possible, however, the low level ev3dev system has no such capability as far as I know. Please check https://github.com/ev3dev/ev3dev/issues/104 . So that means either pull by the framework or application. To avoid the unnecessary overhead, I decided to let application to poll the status. After ev3dev system support event, python-ev3 can easy support too. However, I will keep this thread open until we get a work event system.