Continuation ...
Callbacks
But there is more. You can tell the sensor to inform you about temperature changes without you having to call the get function over and over again. For this the callback function cb_temperature is registered using temperature_register_callback. It will automatically be called if a temperature callback from the temperature sensor is received.
#include <stdio.h>
#include "ip_connection.h"
#include "bricklet_temperature.h"
#define HOST "localhost"
#define PORT 4223
#define UID "XYZ" // Change to your UID
// Callback function for temperature callback
// (parameter has unit °C/100)
void cb_temperature(int16_t temperature, void *user_data) {
(void)user_data; // avoid unused parameter warning
printf("Temperature: %f °C.\n", temperature/100.0);
}
int main() {
// Create IP connection
IPConnection ipcon;
ipcon_create(&ipcon);
// Create device object
Temperature t;
temperature_create(&t, UID, &ipcon);
// Connect to brickd
if(ipcon_connect(&ipcon, HOST, PORT) < 0) {
fprintf(stderr, "Could not connect\n");
exit(1);
}
// Don't use device before ipcon is connected
// Set Period for temperature callback to 1s (1000ms)
// Note: The callback is only called every second if the
// temperature has changed since the last call!
temperature_set_temperature_callback_period(&t, 1000);
// Register temperature callback to function cb_temperature
temperature_register_callback(&t,
TEMPERATURE_CALLBACK_TEMPERATURE,
(void *)cb_temperature,
NULL);
printf("Press key to exit\n");
getchar();
ipcon_destroy(&ipcon); // Calls ipcon_disconnect internally
}
Now someone has to receive incoming data from the socket even if no getter call is currently in progress. In the C code there is the receive thread of the IPConnection that continuously handles incoming data. If a response for a getter call arrives then the receive thread check if any device object such as the Temperature object is currently wating for a response. If yes then the response is passed to the waiting getter call via a queue. If a callback is received, then it is passed over to a second thread via another queue, the callback thread of the IPConnection.
The callback thread takes a callback packet from its queue and checks if any of the device objects has a callback function registered for it. If yes then it calls it with the data from the callback packet. The callbacks cannot be called from the receive thread because then the user provided getter function would not be able to call another getter function of the device. As the receive thread is currently blocked by the callback call it cannot receive the incoming response for the getter call.
But there is even more. If a disconnect of the socket is detected then the receive thread is stopped and the callback thread is told to reconnect. Once the connection is established again the receive thread start receiving incoming data again.
There seems to be post size limit, so to be continued ... |