#!/usr/bin/env python3
#
# BTZen - library to asynchronously access Bluetooth devices.
#
# Copyright (C) 2015-2020 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/>.
#

"""
Display weight data from a scale supporting Bluetooth weight measurement
characteristic.

Connection manager is used for automatic connection to the scale.
"""

import argparse
import asyncio
import logging

import btzen

async def read_weight(scale):
    while True:
        try:
            value = await scale.read()
        except asyncio.CancelledError:
            print('{}: cancelled'.format(scale))
        else:
            print('weight: {}'.format(value))

logging.basicConfig(level=logging.DEBUG)

parser = argparse.ArgumentParser()
parser.add_argument('device', help='MAC address of device')
args = parser.parse_args()

scale = btzen.WeightMeasurement(args.device, notifying=True)

# create connection manager
manager = btzen.ConnectionManager()
manager.add(scale)

task = asyncio.gather(read_weight(scale), manager)
loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(task)
finally:
    # manager also closes all referenced devices, the weight scale in this
    # case
    manager.close()

# vim: sw=4:et:ai
