"""Make the robot smile.

Yahboom's firmware draws a happy face while Bluetooth is connected,
and a sad face when it disconnects. So to make the bot smile, we
connect and simply hold the connection open.

    python smile.py        # smile for 30 seconds
    python smile.py 120    # smile for 2 minutes

Run it:
    Windows:  python smile.py
    Mac:      python3 smile.py

Install bleak first:
    Windows:  python -m pip install bleak
    Mac:      python3 -m pip install bleak
"""
import asyncio
import sys

from bleak import BleakClient, BleakScanner


async def main(seconds):
    print("Looking for the robot...")
    robot = await BleakScanner.find_device_by_filter(
        lambda d, a: d.name and "micro:bit" in d.name)
    if robot is None:
        print("No robot. Is it on? Is the phone app closed?")
        return
    print("Found it:", robot.name)

    async with BleakClient(robot) as car:
        print(f"Connected - the robot is smiling for {seconds}s.")
        try:
            await asyncio.sleep(seconds)
        except KeyboardInterrupt:
            pass
    print("Disconnected - it goes sad again.")


asyncio.run(main(float(sys.argv[1]) if len(sys.argv) > 1 else 30))
