#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# vim: expandtab sw=4 ts=4 sts=4:
#
# Bluetooth Scale Monitor
#
# Author: Joerg Lehmann, nbit Informatik GmbH
#
"""Bluetooth Scale Monitor"""

import json
import datetime
from bluepy.btle import Scanner, DefaultDelegate

LONG = 2147483648L
INT  = 32768

class ScanDelegate(DefaultDelegate):
    def __init__(self):
        DefaultDelegate.__init__(self)

    def ProcessReading(self, mac, value):
        data = {}
        data['datetime'] = datetime.datetime.now().strftime("%d.%m.%Y %H:%M")
        data['w1'] = long(value[0:8],16) - LONG
        data['w2'] = long(value[8:16],16) - LONG
        data['temp'] = int(value[16:20],16) - INT
        data['hum'] = int(value[20:24],16)
        data['accu'] = int(value[24:28],16)

        filename = "/home/beieli/bt-readings/%s.json" % (mac)
        with open(filename,'w') as outfile:
            json.dump(data, outfile, indent=4, sort_keys=True)

    def handleDiscovery(self, dev, isNewDev, isNewData):
        if isNewData:
            for (adtype, desc, value) in dev.getScanData():
                if desc == 'Manufacturer' and value.startswith('1234' ):
                    self.ProcessReading(dev.addr, value[4:])

scanner = Scanner().withDelegate(ScanDelegate())
while True:
    scanner.scan(5)
