#!/usr/bin/env python3
# Matrain publication modification: licensing/source notice added.
# Executable behavior is unchanged except for the adaptations documented below.
# Source: https://github.com/intelino-code/intelino-trainlib-async-py
# Source commit: 298e1fd4091e069180c30f338b4c285b13accbd0
# This software is made available by Innokind, Inc. DBA Intelino, under the
# terms of the Intelino Public License Agreement, Version 1.0 located at
# https://intelino.com/intelino-public-license. BY INSTALLING, DOWNLOADING,
# ACCESSING, USING OR DISTRIBUTING ANY OF THE SOFTWARE, YOU AGREE TO THE TERMS OF
# SUCH LICENSE AGREEMENT.
# Publication adaptation: Bleak 3.0.2向けにreturn_adv=TrueとAdvertisementData.rssiを使います。原例のBLEDevice.rssiは現在のAPIにありません。

"""BLE scanning utility to find nearby intelino trains."""

import asyncio
from typing import List
from bleak import BleakScanner
from bleak.backends.device import BLEDevice
from bleak.backends.scanner import AdvertisementData


def list_devices(title: str, devices: List[tuple[BLEDevice, AdvertisementData]]) -> None:
    print(f"{title} ({len(devices)}):")
    for d, advertisement in devices:
        print(f"{d.address} : {d.name} (RSSI {advertisement.rssi})")


async def scan(timeout: float) -> None:
    advertisements = await BleakScanner.discover(timeout, return_adv=True)
    devices = list(advertisements.values())

    trains = list(filter(lambda item: str(item[0].name).startswith("intelino"), devices))
    others = list(filter(lambda item: not str(item[0].name).startswith("intelino"), devices))

    list_devices("Trains", trains)
    print()
    list_devices("Others", others)


def main():
    asyncio.run(scan(2))


if __name__ == "__main__":
    main()
