"""Step 3 - Turn the lights on and off.

This script is safe. The car does not move.
Start here. If this works, your Bluetooth works.

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

Install bleak first:
    Windows:  python -m pip install bleak
    Mac:      python3 -m pip install bleak

On a Mac, say yes when it asks for Bluetooth.
If you miss it: System Settings > Privacy and Security >
Bluetooth > turn on your Terminal app.
"""
import asyncio

from bleak import BleakClient, BleakScanner

# The robot's letter box. Messages go here.
BOX = "6e400003-b5a3-f393-e0a9-e50e24dcca9e"


async def say(car, command):
    """Send one command to the robot."""
    await car.write_gatt_char(BOX, command.encode() + b"#", response=False)
    await asyncio.sleep(0.05)


async def find_robot():
    """Look for the car and give it back."""
    return await BleakScanner.find_device_by_filter(
        lambda d, a: d.name and "micro:bit" in d.name)


async def main():
    print("Looking for the robot...")
    robot = await find_robot()
    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:
        for name, code in [("red", "G"), ("green", "H"), ("blue", "I")]:
            print("Light is", name)
            await say(car, code)
            await asyncio.sleep(1)
        await say(car, "M")
        print("Lights off.")

    print("Done.")


asyncio.run(main())
