Skip to content

Commit

Permalink
Merge pull request #24 from iomz/async-lock
Browse files Browse the repository at this point in the history
fix: introduce asyncio.Lock
  • Loading branch information
iomz authored Aug 10, 2023
2 parents 87decf8 + 629f684 commit ce71e7a
Showing 1 changed file with 12 additions and 15 deletions.
27 changes: 12 additions & 15 deletions myo/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,12 +143,7 @@ async def command(self, client: BleakClient, cmd: Command):
"""
Command Characteristic
"""
try:
await client.write_gatt_char(Handle.COMMAND.value, cmd.data, True)
except AttributeError:
# wait a bit and try once again
await asyncio.sleep(0.1)
await client.write_gatt_char(Handle.COMMAND.value, cmd.data, True)
await client.write_gatt_char(Handle.COMMAND.value, cmd.data, True)

async def deep_sleep(self, client: BleakClient):
"""
Expand Down Expand Up @@ -241,6 +236,7 @@ def __init__(self, aggregate_all=False, aggregate_emg=False):
self._client = None
self.fv_aggregated = None # for aggregate_all
self.imu_aggregated = None # for aggregate_all
self._lock = asyncio.Lock() # for aggregate_all

@classmethod
async def with_device(cls, mac=None, aggregate_all=False, aggregate_emg=False):
Expand Down Expand Up @@ -337,15 +333,16 @@ async def on_data(self, data):
"""
<> for on_aggregated_data: data is either FVData or IMUData
"""
if isinstance(data, FVData):
self.fv_aggregated = data
elif isinstance(data, IMUData):
self.imu_aggregated = data
# trigger on_aggregated_data when both FVData and IMUData are ready
if all((self.fv_aggregated, self.imu_aggregated)):
await self.on_aggregated_data(AggregatedData(self.fv_aggregated, self.imu_aggregated))
self.fv_aggregated = None
self.imu_aggregated = None
async with self._lock:
if isinstance(data, FVData):
self.fv_aggregated = data
elif isinstance(data, IMUData):
self.imu_aggregated = data
# trigger on_aggregated_data when both FVData and IMUData are ready
if all(d is not None for d in (self.fv_aggregated, self.imu_aggregated)):
await self.on_aggregated_data(AggregatedData(self.fv_aggregated, self.imu_aggregated))
self.fv_aggregated = None
self.imu_aggregated = None

async def on_aggregated_data(self, ad: AggregatedData):
"""
Expand Down

0 comments on commit ce71e7a

Please sign in to comment.