#!/usr/bin/env python

import sys
import traceback

import gobject

import dbus
import dbus.decorators
import dbus.mainloop.glib

usage = """Usage:
python test-emitter.py &
python test-receiver.py
"""

DSTPATH="/com/example/TestService/object"
DSTIFACE="com.example.TestService"


def handle_reply(msg):
    print msg

def handle_error(e):
    print str(e)

def quit_method(obj, loop):
   obj.Exit(dbus_interface=DSTIFACE)
   # exit after waiting a short time for the signal
   gobject.timeout_add(500, loop.quit)
   return False
   

def emit_signal(obj, loop):
   #call the emitHelloSignal method 
   obj.emitHelloSignal(dbus_interface=DSTIFACE,
                          reply_handler = handle_reply, error_handler = handle_error)
   # exit after waiting a short time for the signal
   gobject.timeout_add(1000, quit_method, obj, loop)
   return False

def proxy_signal_cb(self, msg, message, sender):
    print "Received proxy signal %s from %s" % (message, sender)
    print "   ", msg


def hello_signal_handler(self, *args, **kwargs):
    msg = kwargs['hello_msg']
    print "Received signal (by connecting using remote object) for '%s' and it says: %s" % \
        (msg.get_destination(), msg.get_args_list()[1])

def catchall_hello_signals_handler(*args, **kwargs):
    msg = kwargs['hello_msg']
    print "Received a hello signal for '%s' and it says: %s" % \
        (msg.get_destination(), msg.get_args_list()[1])
    
def main(loop):
    bus = dbus.SessionBus()
    try:
        obj  = bus.get_object(DSTIFACE, DSTPATH)
        obj.connect_to_signal("HelloSignal", hello_signal_handler, message_keyword="hello_msg")
    except dbus.DBusException:
        traceback.print_exc()
        print usage
        sys.exit(1)

    bus.add_signal_receiver(catchall_hello_signals_handler, signal_name="HelloSignal", message_keyword="hello_msg")

    #p = bus.get_object (DSTIFACE, DSTPATH)
    #p.connect_to_signal ("HelloSignal", proxy_signal_cb, sender_keyword="sender", message_keyword="message");

    # Tell the remote object to emit the signal after a short delay

    gobject.timeout_add(1000, emit_signal, obj, loop)

if __name__ == '__main__':
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
    loop = gobject.MainLoop()
    main (loop)
    loop.run()
