#!/usr/bin/python

from __future__ import absolute_import, print_function, unicode_literals

'''
Thermometer test script
'''

import gobject

import sys
import dbus
import dbus.service
import dbus.mainloop.glib
from optparse import OptionParser, make_option
import bluezutils

class Watcher(dbus.service.Object):
	@dbus.service.method("org.bluez.ThermometerWatcher",
					in_signature="oa{sv}", out_signature="")
	def MeasurementReceived(self, device, measure):
		print("%s measurement received from %s" % (measure["Measurement"], device))
		print("Exponent: ", measure["Exponent"])
		print("Mantissa: ", measure["Mantissa"])
		print("Unit: ", measure["Unit"])

		if "Time" in measure:
			print("Time: ", measure["Time"])

		if "Type" in measure:
			print("Type: ", measure["Type"])

def properties_changed(interface, changed, invalidated):
	if interface != "org.bluez.Thermometer":
		return
	for name, value in changed.iteritems():
		print("Property %s changed:  %s" % (name, str(value)))

if __name__ == "__main__":
	dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

	bus = dbus.SystemBus()

	option_list = [
		make_option("-i", "--adapter", action="store",
			type="string", dest="adapter"),
		make_option("-b", "--device", action="store",
			type="string", dest="address"),
		]

	parser = OptionParser(option_list=option_list)

	(options, args) = parser.parse_args()

	if not options.address:
		print("Usage: %s [-i <adapter>] -b <bdaddr> [command]" % (sys.argv[0]))
		print("Possible commands:")
		print("\tEnableIntermediateMeasurement")
		sys.exit(1)

	adapter = bluezutils.find_adapter(options.adapter)
	adapter_path = adapter.object_path
	thermometer_manager = dbus.Interface(bus.get_object("org.bluez",
				adapter_path), "org.bluez.ThermometerManager")

	device_path = adapter.FindDevice(options.address)

	bus.add_signal_receiver(properties_changed, bus_name="org.bluez",
			path=device_path,
			dbus_interface="org.freedesktop.DBus.Properties",
			signal_name="PropertiesChanged")

	path = "/test/watcher"
	watcher = Watcher(bus, path)

	thermometer_manager.RegisterWatcher(path)

	if len(args) > 0:
		if args[0] == "EnableIntermediateMeasurement":
			thermometer_manager.EnableIntermediateMeasurement(path)
		else:
			print("unknown command")
			sys.exit(1)

	mainloop = gobject.MainLoop()
	mainloop.run()