#!/usr/bin/env python3
#
# BTZen - Bluetooth Smart sensor reading library.
#
# Copyright (C) 2015-2018 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 btzen


async def read_sensor(name, reader):
    await reader.connect()
    while True:
        t1 = loop.time()
        value = await reader.read()
        value = '{:.1f}'.format(value)
        t2 = loop.time()
        print('{}: {} ({:.4f}s)'.format(name, value, t2 - t1))
        await asyncio.sleep(-loop.time() % 1)

async def read_accelerometer(reader):
    await reader.connect()
    reader.set_interval(0.1)
    while True:
        t1 = loop.time()
        values = await reader.read()
        values = ', '.join('{:.4f}'.format(v) for v in values)
        t2 = loop.time()
        print('accelerometer: {} ({:.4f}s)'.format(values, t2 - t1))

async def read_button(reader):
    await reader.connect()
    while True:
        t1 = loop.time()
        value = await reader.read()
        t2 = loop.time()
        print('button: {} ({:.4f}s)'.format(value, t2 - t1))

parser = argparse.ArgumentParser()
parser.add_argument(
    '--verbose', default=False, action='store_true',
    help='show debug log'
)
parser.add_argument('device', help='MAC address of device')
args = parser.parse_args()

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

print('connecting to {}...'.format(args.device))

names = ['pressure', 'temperature', 'humidity', 'light']
classes = [
    btzen.Pressure, btzen.Temperature, btzen.Humidity, btzen.Light,
]
readers = ((n, c(args.device)) for c, n in zip(classes, names))
readers = {n: r for n, r in readers if r is not None}
print('sensors initialized')

loop = asyncio.get_event_loop()
sensors = sorted([(n, r) for n, r in readers.items() if r])
tasks = [read_sensor(n, r) for n, r in sensors]

reader = readers['accelerometer'] = btzen.Accelerometer(args.device, notifying=True)
tasks.append(read_accelerometer(reader))

reader = readers['button'] = btzen.Button(args.device, notifying=True)
tasks.append(read_button(readers['button']))

try:
    loop.run_until_complete(asyncio.gather(*tasks))
finally:
    for r in readers.values():
        r.close()

# vim: sw=4:et:ai
