#!/usr/bin/env python3
#
# BTZen - library to asynchronously access Bluetooth devices.
#
# Copyright (C) 2015-2022 by Artur Wroblewski <wrobell@riseup.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import argparse
import asyncio
import logging
import uvloop
from contextlib import asynccontextmanager
from datetime import datetime

import btzen

async def battery_level(battery: btzen.DeviceTrigger[btzen.Service, int]) -> None:
    async for value in btzen.read_all(battery):
        print('{}: {}%'.format(datetime.now(), value))

async def read_data(
    mac: str, interface: str, address_type: btzen.AddressType
) -> None:

    dev = btzen.battery_level(mac)
    dev = btzen.set_address_type(dev, address_type=address_type)
    async with btzen.connect([dev], interface=interface) as session:
        await asyncio.gather(session, battery_level(dev))

parser = argparse.ArgumentParser()
parser.add_argument(
    '--verbose', default=False, action='store_true',
    help='show debug log'
)
parser.add_argument(
    '-i', '--interface', default='hci0',
    help='Host controller interface (HCI)'
)
parser.add_argument(
    '-a', '--address-type', choices=list(btzen.AddressType), default='public',
    type=btzen.AddressType,
    help='Device connection address type'
)
parser.add_argument('device', help='MAC address of device')
args = parser.parse_args()

level = logging.DEBUG if args.verbose else logging.INFO
logging.basicConfig(level=level)

uvloop.install()
asyncio.run(read_data(args.device, args.interface, args.address_type))

# vim: sw=4:et:ai
