# -*- coding: utf-8 -*-
"""
Notifications
-------------

Example showing how to add notifications to a characteristic and handle the responses.

Updated on 2019-07-03 by hbldh <henrik.blidh@gmail.com>

"""

import sys
import logging
import asyncio
import platform

from bleak import BleakClient
from bleak import _logger as logger


CHARACTERISTIC_UUID = "f000aa65-0451-4000-b000-000000000000"  # <--- Change to the characteristic you want to enable notifications from.
ADDRESS = (
    "24:71:89:cc:09:05"  # <--- Change to your device's address here if you are using Windows or Linux
    if platform.system() != "Darwin"
    else "B9EA5233-37EF-4DD6-87A8-2A875E821C46"  # <--- Change to your device's address here if you are using macOS
)
if len(sys.argv) == 3:
    ADDRESS = sys.argv[1]
    CHARACTERISTIC_UUID = sys.argv[2]


def notification_handler(sender, data):
    """Simple notification handler which prints the data received."""
    print("{0}: {1}".format(sender, data))


async def run(address, debug=False):
    if debug:
        import sys

        l = logging.getLogger("asyncio")
        l.setLevel(logging.DEBUG)
        h = logging.StreamHandler(sys.stdout)
        h.setLevel(logging.DEBUG)
        l.addHandler(h)
        logger.addHandler(h)

    async with BleakClient(address) as client:
        logger.info(f"Connected: {client.is_connected}")

        await client.start_notify(CHARACTERISTIC_UUID, notification_handler)
        await asyncio.sleep(5.0)
        await client.stop_notify(CHARACTERISTIC_UUID)


if __name__ == "__main__":
    import os

    os.environ["PYTHONASYNCIODEBUG"] = str(1)
    loop = asyncio.get_event_loop()
    # loop.set_debug(True)
    loop.run_until_complete(run(ADDRESS, True))

[(60, 'asyncio.get_event_loop', 'asyncio.get_event_loop', False, 'import asyncio\n'), (24, 'platform.system', 'platform.system', False, 'import platform\n'), (41, 'logging.getLogger', 'logging.getLogger', False, 'import logging\n'), (43, 'logging.StreamHandler', 'logging.StreamHandler', False, 'import logging\n'), (46, 'bleak._logger.addHandler', 'logger.addHandler', True, 'from bleak import _logger as logger\n'), (48, 'bleak.BleakClient', 'BleakClient', False, 'from bleak import BleakClient\n'), (49, 'bleak._logger.info', 'logger.info', True, 'from bleak import _logger as logger\n'), (52, 'asyncio.sleep', 'asyncio.sleep', False, 'import asyncio\n')]