summaryrefslogtreecommitdiff
path: root/frameworks/middleware/examples/dbus/ping-server.c
blob: 36dd1226d1de21ddf3a96e7e1693ebb2235fa6c5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <dbus/dbus.h>
#include <dbus/dbus-glib.h>
#include <time.h>

static DBusHandlerResult signal_filter
		(DBusConnection *connection, DBusMessage *message, void *user_data);

int main(int argc, char **argv)
{
	GMainLoop *loop;
	DBusConnection *bus;
	DBusError error;

	loop = g_main_loop_new (NULL, FALSE);
	dbus_error_init (&error);
	bus = dbus_bus_get (DBUS_BUS_SESSION, &error);

	if (!bus) {
		g_warning ("Failed to connect to the D-BUS daemon: %s", error.message);
		dbus_error_free (&error);
		return 1;
	}

	dbus_connection_setup_with_g_main (bus, NULL);
	/* listening to messages from all objects as no path is specified */
	dbus_bus_add_match (bus, "type='signal',interface='de.linutronix.Ping'",
		&error);
	dbus_connection_add_filter (bus, signal_filter, loop, NULL);
	g_main_loop_run (loop);

	return 0;
}

static DBusHandlerResult signal_filter
		(DBusConnection *connection, DBusMessage *message, void *user_data)
{
	/* User data is the event loop we are running in */
	GMainLoop *loop = user_data;

	/* A signal from the bus saying we are about to be disconnected */
	if (dbus_message_is_signal(message, "org.freedesktop.Local",
		"Disconnected"))
	{
		/* Tell the main loop to quit */
		g_main_loop_quit (loop);
		/* We have handled this message, don't pass it on */
		return DBUS_HANDLER_RESULT_HANDLED;
	}
	else if (dbus_message_is_signal (message, "de.linutronix.Ping", "Ping"))
	{
		DBusError error;
		char *s;

		dbus_error_init (&error);

		if (dbus_message_get_args(message, &error, DBUS_TYPE_STRING, &s,
			DBUS_TYPE_INVALID))
		{
			struct timespec rx_time;
			clock_gettime(CLOCK_MONOTONIC, &rx_time);
			g_print("ping received: %s - %d:%d\n", s, rx_time.tv_sec,
				rx_time.tv_nsec/1000);
			// dbus_free (s);
		} else {
			g_print("ping received, but error getting message: %s\n", error.message);
			dbus_error_free (&error);
		}
		return DBUS_HANDLER_RESULT_HANDLED;
	}
	return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}