typedef void(*xbee_t_conCallback)(struct xbee *xbee, struct xbee_con *con, struct xbee_pkt **pkt, void **data);
xbee_err xbee_conCallbackSet(struct xbee_con *con, xbee_t_conCallback newCallback, xbee_t_conCallback *oldCallback);
xbee_err xbee_conCallbackGet(struct xbee_con *con, xbee_t_conCallback *curCallback);
xbee_conCallbackSet() allows you to associate a callback function with a connection, whilst retrieving the current callback.
con must be a valid connection, returned from xbee_conNew(). newCallback must be either NULL (to disable callbacks), or non-NULL to enable callbacks, with the given function address. oldCallback can be NULL to indicate that you do not wish to retrieve the previously assigned callback.
xbee_conCallbackGet() allows you to retrieve the callback function that is currently assigned to the given connection.
This means that if a single callback function is associated with multiple connections, static variables will be unsafe, and the developer should instead use the void **data that is provided. The data parameter is initialized to NULL, so you may safely initialize this from within the callback function, or alternatively from outside, by calling xbee_conDataSet().
NOTE: you must dereference this argument once. If you leave the argument alone, then libxbee will automatically call xbee_pktFree() on the packet after the callback has completed. If you instead re-assign NULL to it, libxbee will not call xbee_pktFree() on the packet. This is useful if you wish to postpone processing, in which case you must later call xbee_pktFree(). See the EXAMPLE section for more information.
#include <xbee.h> void myCallback(struct xbee *xbee, struct xbee_con *con, struct xbee_pkt **pkt, void **data) { printf("received data for connection @ %p\n", con); xbee_conTx(con, "Hello!\n"); } struct xbee *xbee; struct xbee_con *con; /* initialize xbee, using xbee_setup() */ /* initialize con, using xbee_conNew() */ if (xbee_conCallbackSet(con, myCallback, NULL) != XBEE_ENONE) return;
struct myStruct { int counter; struct xbee_pkt *pkt; }; void myCallback(struct xbee *xbee, struct xbee_con *con, struct xbee_pkt **pkt, void **data) { struct myStruct *ms; /* allocate storage for the counter & packet */ if (!(*data)) { if ((ms = malloc(sizeof(*ms))) == NULL) return; /* error */ /* keep hold of the storage */ *data = ms; } else { ms = *data; } /* if we are already holding a packet, print a message and return (libxbee will free the packet) */ if (ms->pkt) { printf("already holding a packet...\n"); return; } /* otherwise increment the counter, and hold on to the packet */ ms->counter++; ms->pkt = *pkt; printf("received %d packets for connection @ %p\n", ms->a, con); xbee_conTx(con, "Hello!\n"); /* don't let libxbee free our packet */ *pkt = NULL; } /* observe the data using xbee_conDataGet() */