55 lines
1.8 KiB
Python
55 lines
1.8 KiB
Python
import asyncio
|
|
from .driver import BMA400
|
|
|
|
def is_landscape(accel):
|
|
x, y, z = accel
|
|
# Return True if device is in landscape orientation
|
|
return abs(x) > abs(y)
|
|
|
|
def is_inverted(accel):
|
|
x, y, z = accel
|
|
# Return True if device is in landscape orientation
|
|
return 0 > abs(y)
|
|
|
|
async def detect_orientation_flip(current_state: bool, eval_func, flip_delay: float = 1.0, sensor = None) -> bool:
|
|
"""
|
|
Asynchronously detect orientation flip using the BMA400 accelerometer.
|
|
|
|
Args:
|
|
current_state (bool): The current orientation state.
|
|
eval_func (Callable[[tuple], bool]): A function that evaluates the acceleration (x, y, z)
|
|
and returns True if flipped, False otherwise.
|
|
flip_delay (float): Delay in seconds after detecting a flip before confirming the state change.
|
|
|
|
Returns:
|
|
bool: The updated orientation state.
|
|
"""
|
|
try:
|
|
# Initialize sensor if not provided
|
|
if sensor is None:
|
|
sensor = BMA400()
|
|
|
|
sensor.power_mode = BMA400.LOW_POWER_MODE
|
|
sensor.output_data_rate = BMA400.ACCEL_12_5HZ
|
|
sensor.acc_range = BMA400.ACC_RANGE_2
|
|
sensor.oversampling_rate = BMA400.OVERSAMPLING_0
|
|
|
|
while True:
|
|
accel = sensor.acceleration
|
|
flipped = eval_func(accel)
|
|
|
|
if flipped != current_state:
|
|
# Possible orientation change detected, wait for confirmation
|
|
await asyncio.sleep(flip_delay)
|
|
|
|
# Check again to confirm
|
|
accel = sensor.acceleration
|
|
if eval_func(accel) == flipped:
|
|
return flipped
|
|
|
|
await asyncio.sleep(0.1) # Polling interval
|
|
|
|
except Exception as e:
|
|
print(f"Error: {e}")
|
|
return current_state
|