Skip to content

Commit 02187d4

Browse files
committed
Make use of polling functionality in 16-ev3dev kernel
Introduces the following functions: * Motor.wait(condition), * Motor.wait_while(state, timeout=None) * Motor.wait_until(state, timeout=None) Make the following possible: m.wait_while('running') m.wait_until('stalled') Closes #230
1 parent ea66472 commit 02187d4

1 file changed

Lines changed: 54 additions & 0 deletions

File tree

‎ev3dev/core.py‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@
4646
import ctypes
4747
import re
4848
import stat
49+
import select
50+
import time
4951
from os.path import abspath
5052
from struct import pack, unpack
5153
from subprocess import Popen
@@ -314,6 +316,8 @@ def __init__(self, address=None, name_pattern=SYSTEM_DEVICE_NAME_CONVENTION, nam
314316

315317
# ~autogen
316318

319+
self._poll = None
320+
317321
# ~autogen generic-get-set classes.motor>currentClass
318322

319323
@property
@@ -806,6 +810,56 @@ def reset(self, **kwargs):
806810

807811
# ~autogen
808812

813+
def wait(self, cond):
814+
"""
815+
Blocks until cond(self.state) is True. The condition is checked when
816+
there is an I/O event related to the state attribute.
817+
"""
818+
819+
if self._poll is None:
820+
if self._state is None:
821+
self._state = self._attribute_file_open('state')
822+
self._poll = select.poll()
823+
self._poll.register(self._state, select.POLLPRI)
824+
825+
while True:
826+
# wait for an event
827+
for _ in self._poll.poll():
828+
if cond(self.state): return
829+
830+
def wait_until(self, s, timeout=None):
831+
"""
832+
Blocks until s is in self.state, or timeout (in seconds) is expired.
833+
834+
Example::
835+
836+
m.wait_until('stalled')
837+
"""
838+
tic = time.time()
839+
def done(state):
840+
if s in state:
841+
return True
842+
return (timeout is not None) and (time.time() > tic + timeout)
843+
844+
self.wait(done)
845+
846+
def wait_while(self, s, timeout=None):
847+
"""
848+
Blocks while s is in self.state, or timeout (in seconds) is expired.
849+
850+
Example::
851+
852+
m.wait_while('running')
853+
"""
854+
tic = time.time()
855+
856+
def done(state):
857+
if s not in state:
858+
return True
859+
return (timeout is not None) and (time.time() > tic + timeout)
860+
861+
self.wait(done)
862+
809863
def list_motors(name_pattern=Motor.SYSTEM_DEVICE_NAME_CONVENTION, **kwargs):
810864
"""
811865
This is a generator function that enumerates all tacho motors that match

0 commit comments

Comments
 (0)