2017-02-17 5 views
0

Windows 컴퓨터에서 asyncio와 함께 pyserial을 사용하려고합니다.Pyserial 및 asyncio

https://stackoverflow.com/a/27927704/1629704에 의해 영감을 받아 주신 제 코드는 수신되는 데이터의 직렬 포트를 지속적으로보고 있습니다.

# This coroutine is added as a task to the event loop. 
@asyncio.coroutine 
def get_from_serial_port(self): 
    while 1: 
     serial_data = yield from self.get_byte_async() 
     <doing other stuff with serial_data> 

# The method which gets executed in the executor 
def get_byte(self): 
    data = self.s.read(1) 
    time.sleep(0.5) 
    tst = self.s.read(self.s.inWaiting()) 
    data += tst 
    return data 

# Runs blocking function in executor, yielding the result 
@asyncio.coroutine 
def get_byte_async(self): 
    with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor: 
     res = yield from self.loop.run_in_executor(executor, self.get_byte) 
     return res 

직렬 데이터가 반환 된 후. coroutine get_byte_async은 while 루프 내에서 호출되어 새 실행 프로그램을 만듭니다. 나는 새로운 스레드를 만드는 것이 비싸다는 것을 항상 배웠다. 그래서 나는 다른 접근법을 취해야한다고 생각하지만, 어떻게해야할지 모르겠다. 나는이 기사를 읽었습니다. https://hackernoon.com/threaded-asynchronous-magic-and-how-to-wield-it-bba9ed602c32#.964j4a5s7

그리고 나는 다른 스레드에서 직렬 포트를 읽어야 할 필요가 있다고 생각합니다. 그러나 직렬 데이터를 "main"루프로 다시 가져 오는 방법은 무엇입니까?

답변

0

당신은 기본 실행기를 사용하고 asyncio lockget_byte에 대한 액세스를 잠글 수 있습니다 :

async def get_byte_async(self): 
    async with self.lock: 
     return await self.loop.run_in_executor(None, self.get_byte) 

을하거나 한 번 자신의 실행기를 만들 :

async def get_byte_async(self): 
    if self.executor is None: 
     self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=1) 
    return await self.loop.run_in_executor(self.executor, self.get_byte)