#!/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/>.
#

import argparse
import asyncio
import logging
import uvloop
from datetime import datetime

import btzen
import btzen.thingy52

async def read_sensor(name, sensor):
    while True:
        value = await sensor.read()
        if isinstance(value, (float, int)):
            print_data(name, '{:.1f}'.format(value))
        else:
            print_data(name, '{}'.format(value))

async def battery_level(battery):
    while True:
        value = await battery.read()
        print_data('battery level', value)
        await asyncio.sleep(1)

def print_data(name, value):
    print('{} {}: {}'.format(datetime.now(), name, value))


#
# sensor definitions
#
SENSORS = [
    ('pressure', btzen.thingy52.Pressure),
    ('temperature', btzen.thingy52.Temperature),
    ('humidity', btzen.thingy52.Humidity),
    ('light', btzen.thingy52.Light),
]

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(
    '-t', '--interval', default=1.0, type=float,
    help='Sensor data read interval'
)
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)

# get the loop first
uvloop.install()
loop = asyncio.get_event_loop()

# initialize all Thingy52 sensors
items = [(name, cls(args.device, notifying=True)) for name, cls in SENSORS]
sensors =  [sensor for _, sensor in items]
for s in sensors:
    s.set_interval(args.interval)

# create tasks reading the sensor data
tasks = [read_sensor(name, sensor) for name, sensor in items]

battery = btzen.BatteryLevel(args.device, notifying=True)
tasks.append(battery_level(battery))

# create connection manager
manager = btzen.ConnectionManager(interface=args.interface)
manager.add(battery, *sensors)

try:
    loop.run_until_complete(asyncio.gather(manager, *tasks))
finally:
    # connection manager closes all sensors
    manager.close()

# vim: sw=4:et:ai
