Dbus structure and method calls in C - c

I am starting to create a dbus application in C to interface with bluez. I am new to dbus and I am a little confused as how to correctly structure my application with dbus.
The first question is related to the Service, Interface, and Object path in dbus. Bluez Adapter API has the org.bluez service, a org.bluez.Adapter1 interface, and a number of methods and properties. If I wanted to call the void StopDiscovery() method, would the following be the correct call?
DBusPendingCall * pending;
// create a new method call and check for errors
msg = dbus_message_new_method_call("org.bluez",
"/", // object to call on
"org.bluez.Adapter1", // interface to call on
"StopDiscovery"); // method name
// send message and get a handle for a reply
if (!dbus_connection_send_with_reply (m_dbus_conn, msg, &pending, -1))
{
//err
}
If this is the case, when does the object path come into play?
The follow on to this is how to go about receiving information back from dbus. I've seen a few examples with a DBusPendingCall * however the function has dbus_pending_call_block() so the function blocks until the data is returned. If I wanted to do multiple calls and not block I would need to make a list of DBPendingCall pointers and check each one? Are there any callbacks?
Thanks

I did create an example showing the non-blocking call based on the dbus watch and timeout mechanism, in response to the SO question dbus watch and timeout examples. Basically you run a unix select() loop and everything is dispatched around it.
And I did not touch the multiple outstanding pending-call part. I assume one way is to check each pending-call to see whether it is completed when the watched event is received. Checking pending complete is non-blocking. If you keep a small number of outstanding pending calls it should be ok, though that is not an efficient solution if the number becomes big.
It looks like according to the API document, a better solution is to use dbus_pending_call_set_notify() to register a callback to a pending call.

So it appears that both the object path and the interface are required when talking to bluez over dbus.
// create a new method call for the adapter
msg = dbus_message_new_method_call("org.bluez",
"/org/bluez/hci0", // object to call on
"org.bluez.Adapter1", // interface to call on
"StopDiscovery"); // method name
// create a new method call for a characteristic on
// a given service
msg = dbus_message_new_method_call("org.bluez",
"/org/bluez/hci0/dev_12_34_56_78_9A_BC/service0010/char0011",
"org.bluez.GattCharacteristic1",
"StartNotify");
The select on Unix sockets for pending looks like a solid, scaleable way to go, I will consider this architecture as the application grows

Related

What is difference between MQTTAsync_onSuccess and MQTTAsync_deliveryComplete callbacks?

I'm learning about MQTT (specifically the paho C library) by reading and experimenting with variations on the async pub/sub examples.
What's the difference between the MQTTAsync_deliveryComplete callback that you set with MQTTAsync_setCallbacks() vs. the MQTTAsync_onSuccess or MQTTAsync_onSuccess5 callbacks that you set in the MQTTAsync_responseOptions struct that you pass to MQTTAsync_sendMessage() ?
All seem to deal with "successful delivery" of published messages, but from reading the example code and doxygen, I can't tell how they relate to or conflict with or supplement each other. Grateful for any guidance.
Basically MQTTAsync_deliveryComplete and MQTTAsync_onSuccess do the same, they notify you via callback about the delivery of a message. Both callbacks are executed asynchronously on a separate thread to the thread on which the client application is running.
(Both callbacks are even using the same thread in the case of the current version of the Paho client, but this is a non-documented implementation detail. This thread used by MQTTAsync_deliveryComplete and MQTTAsync_onSuccess is of course not the application thread otherwise it would not be an asynchronous callback).
The difference is that MQTTAsync_deliveryComplete callback is set once via MQTTAsync_setCallbacks and then you are informed about every delivery of a message.
In contrast to this, the MQTTAsync_onSuccess informs you once for exactly the message that you send out via MQTTAsync_sendMessage().
You can even define both callbacks, which will both be called when a message is delivered.
This gives you the flexibility to choose the approach that best suits your needs.
Artificial example
Suppose you have three different functions, each sending a specific type of message (e.g. sendTemperature(), sendHumidity(), sendAirPressure()) and in each function you call MQTTAsync_sendMessage, and after each delivery you want to call a matching callback function, then you would choose MQTTAsync_onSuccess. Then you do not need to keep track of MQTTAsync_token and associate that with your callbacks.
For example, if you want to implement a logging function instead, it would be more useful to use MQTTAsync_deliveryComplete because it is called for every delivery.
And of course one can imagine that one would want to have both the specific one with some actions and the generic one for logging, so in this case both variants could be used at the same time.
Documentation
You should note that MQTTAsync_deliveryComplete explicitly states in its documentation that it takes into account the Quality of Service Set. This is not the case in the MQTTAsync_onSuccess documentation, but of course it does not mean that this is not done in the implementation. But if this is important, you should explicitly check the source code.

What's the purpose of the serial parameter in the Wayland API?

I've been working with the Wayland protocol lately and many functions include a unit32_t serial parameter. Here's an example from wayland-client-protocol.h:
struct wl_shell_surface_listener {
/**
* ping client
*
* Ping a client to check if it is receiving events and sending
* requests. A client is expected to reply with a pong request.
*/
void (*ping)(void *data,
struct wl_shell_surface *wl_shell_surface,
uint32_t serial);
// ...
}
The intent of this parameter is such that a client would respond with a pong to the display server, passing it the value of serial. The server would compare the serial it received via the pong with the serial it sent with the ping.
There are numerous other functions that include such a serial parameter. Furthermore, implementations of other functions within the API often increment the global wl_display->serial property to obtain a new serial value before doing some work. My question is, what is the rationale for this serial parameter, in a general sense? Does it have a name? For example, is this an IPC thing, or a common practice in event-driven / asynchronous programming? Is it kind of like the XCB "cookie" concept for asynchronous method calls? Is this technique found in other programs (cite examples please)?
Another example is in glut, see glutTimerFunc discussed here as a "common idiom for asynchronous invocation." I'd love to know if this idiom has a name, and where (good citations please) it's discussed as a best practice or technique in asynchronous / even-driven programming, such as continuations or "signals and slots." Or, for example, how shared resource counts are just integers, but we consider them to be "semaphores."
You may find this helpful
Some actions that a Wayland client may perform require a trivial form
of authentication in the form of input event serials. For example, a
client which opens a popup (a context menu summoned with a right click
is one kind of popup) may want to "grab" all input events server-side
from the affected seat until the popup is dismissed. To prevent abuse
of this feature, the server can assign serials to each input event it
sends, and require the client to include one of these serials in the
request.
When the server receives such a request, it looks up the input event
associated with the given serial and makes a judgement call. If the
event was too long ago, or for the wrong surface, or wasn't the right
kind of event — for example, it could reject grabs when you wiggle the
mouse, but allow them when you click — it can reject the request.
From the server's perspective, they can simply send a incrementing
integer with each input event, and record the serials which are
considered valid for a particular use-case for later validation. The
client receives these serials from their input event handlers, and can
simply pass them back right away to perform the desired action.
https://wayland-book.com/seat.html#event-serials
As Hans Passant and Tom Zych state in the comments, the argument is distinguishes one asynchronous invocation from another.
I'm still curious about the deeper question, which is if this technique is one commonly used in asynchronous / event-driven software, and if it has a well-known name.

How does socketIO handle the functions I give to him?

It's a project including angularJs, nodeJs and mongoDb.
I have this client side code :
webSocket.emit('createNode', node, function(node){
/* ^ */
/* Where does this goes ? */
$scope.nodes.push(node);
});
And this server side code :
socket.on('createNode', function(node, callback) {
/* ^ */
/* Where does this comes from ? */
mongo.connect("mongodb://localhost:27017/test", function(err, db) {
db.collection('nodes').insertOne(node, function(error, data){
callback(node);
});
});
});
I want to know how does socketIo do to run the function I gave him and how can I execute a piece of code after an emit success without calling it explicitly server-side.
It's the so called acknowledgement. You can check the docs here: http://socket.io/docs/#sending-and-getting-data-(acknowledgements).
It's very simple idea - when you emit something from the client, the client saves your acknowledgment callback and maps it to your specific emit call. "emit createNode - function() {}". Then it sends the info to the server and marks that this emit needs callback. When the server calls it, it's not actually calling the function on the client, it's just internally saying to socket "okay send back the acknowledgment".
Socket.IO actually makes another emit back from the server and because it's marked as acknowledgment, the client treats it like so. It browses the map it has created and calls the function that was stored previously.
It's all done internally so that you don't write logic for waiting for that callback - it's all under the hood for you.
Back to your last question - "how can I execute a piece of code after an emit success". There is no such a thing as "emit success". The client does not know if the emit reached the server or what has happened there. Sockets are simply a channel that sends information - they do not care what's going on next. That's the way it's built.
If you need to know if server got your command, you must send back that information to the client. Which means, in terms of Socket.IO, that you should use those acknowledgments and explicitly notify about success.
But don't be afraid of that - explicitly does NOT mean you are calling client side function, it's just notifying client that all went well and command was received. This approach is very powerful as you can pass params about the result of the command, stating if it was valid or not, if the result is success or not. So go ahead, give it a try :)

Transferring data to/from a callback from/to a worker thread

My current application is a toy web service written in C designed to replicate the behaviour of http://sprunge.us/ (takes data in via http POST, stores it to disk, returns the client a url to the data - also serves data that has been previously stored upon request).
The application is structured such that a thread pool is instantiated with worker threads (just a function pointer that takes a void* parameter) and a socket is opened to listen to incoming connections. The main loop of the program comprises a sock = accept(...) call and then a pool_add_task(worker_function_parse_http, sock) to enable requests to be handled quickly.
The parse_http worker parses the incoming request and either adds another task to the work queue for storing the data (POST) or serving previously stored data (GET).
My problem with this approach stems from the use of the http-parser library which uses a callback design to return parsed data (all http parsers that I looked at used this style). The problem I encounter is as such:
My parse_http worker:
Buffers data from the accepted socket (the function's only parameter, at this stage)
Sets up a http-parser object as per its API, complete with setting callback functions for it to call when it finishes parsing the URL or BODY or whatever. (These functions are of a fixed type signature defined by the http-parser lib, with a pointer to a buffer containing the parsed data relevant to the call, so I can't pass in my own variables and solve the problem that way. These functions also return a status code to the http parser, so I can't use the return values either. The suggested way to get data out of the parser for later use is to copy it out to a global variable during the callback - fun with multiple threads.)
Execute the parser on the buffered socket data. At this stage, the parser is expected to call its set up callbacks when it parses different sections of the buffer. The callback is supplied with parsed data relevant to each callback (e.g. BODY segment supplied to body_parsed callback function).
Well, this is where the problem shows. The parser has executed, but I don't have any access to the parsed data. Here is where I would add a new task to the queue with a worker function to store the received body data or another to handle the GET request for previously stored data. These functions would need to be supplied with both the parsed information (POST data or GET url) as well as the accepted socket so that the now delegated work can respond to the request and close the connection.
Of course, the obvious solution to the problem is simply to not use this thread-pool model with asynchronous practices, but I would like to know, for now and for later, how best to tackle this problem.
How can I get the parsed data from these callbacks back to the worker thread function. I've considered simply making my on_url_parsed and on_body_parsed do the rest of the application's job (storing and retrieving data), but of course I no longer have the client's socket to respond back to in these contexts.
If needed, I can post up the source code to the project when I get the chance.
Edit: It turns out that it is possible to access a user defined void * from within the callbacks of this particular http-parser library as the callbacks are passed a reference to the caller (the parser object) which has a user-definable data field.
A well-designed callback interface would provide for you to give the parser a void * which it would pass on to each of the callback functions when it calls them. The callback functions you provide know what type of object it points to (since you provide both the data pointer and the function pointers), so they can cast and properly dereference it. Among other advantages, this way you can provide for the callbacks to access a local variable of the function that initiates the parse, instead of having to rely on global variables.
If the parser library you are using does not have such a feature (and you don't want to switch to a better-designed one), then you can probably use thread-local storage instead of global variables. How exactly you would do that depends on your thread library and compiler, or you could roll your own by using thread identifiers as keys to thread-specific slots in some global data structure (a hash table for instance).

Is Socket.SendAsync thread safe effectively?

I was fiddling with Silverlight's TCP communication and I was forced to use the System.Net.Sockets.Socket class which, on the Silverlight runtime has only asynchronous methods.
I was wondering what happens if two threads call SendAsync on a Socket instance in a very short time one from the other?
My single worry is to not have intermixed bytes going through the TCP channel.
Being an asynchronous method I suppose the message gets placed in a queue from which a single thread dequeues so no such things will happen (intermixing content of the message on the wire).
But I am not sure and the MSDN does not state anything in the method's description. Is anyone sure of this?
EDIT1 : No, locking on an object before calling SendAsync such as :
lock(this._syncObj)
{
this._socket.SendAsync(arguments);
}
will not help since this serializes the requests to send data not the data actually sent.
In order to call the SendAsync you need first to have called ConnectAsync with an instance of SocketAsyncEventArgs. Its the instance of SocketAsyncEventArgs which represents the connection between the client and server. Calling SendAsync with the same instance of SocketAsyncEventArgs that has just been used for an outstanding call to SendAsync will result in an exception.
It is possible to make multiple outstanding calls to SendAsync of the same Socket object but only using different instances of SocketAsyncEventArgs. For example (in a parallel universe where this might be necessay) you could be making multiple HTTP posts to the same server at the same time but on different connections. This is perfectly acceptable and normal neither client nor server will get confused about which packet is which.

Resources