Aller au contenu principal

Hello World en C

Ce tutoriel montre l'utilisation des bindings C FFI de HDDS pour une communication publish-subscribe basique.

Prérequis : un compilateur C, make et une chaîne Rust stable récente (1.89 ou plus pour le build de l'espace de travail, à cause de la dépendance rusqlite 0.41.1) : la bibliothèque C se compile depuis les sources HDDS avec Cargo. Voir Installation Linux.

API bas niveau

L'API C opere sur des octets bruts encodés en CDR. Pour des données typées, utilisez hdds_gen pour générer le code de sérialisation, ou utilisez directement l'API Rust.

Prérequis réseau

La découverte utilise le multicast UDP. Si l'abonné ne reçoit rien et qu'aucune erreur n'apparaît, la découverte n'a probablement pas lieu (VPN, conteneur, pare-feu). Pour un test sur une seule machine, lancez les deux programmes avec HDDS_INTERFACE=lo. Voir Prérequis réseau.

Étape 0 : Compiler la bibliothèque C​

git clone https://git.hdds.io/hdds/hdds.git
cd hdds
make sdk-c # équivaut à : cargo build --release -p hdds-c

Cela produit, dans le dépôt HDDS :

FichierRôle
sdk/c/include/hdds.hL'en-tête public (à utiliser)
target/release/libhdds_c.aBibliothèque statique : aucune dépendance à l'exécution
target/release/libhdds_c.soBibliothèque partagée (.dylib sur macOS)

crates/hdds-c/hdds.h est l'en-tête tel que cbindgen le génère pendant la compilation ; sdk/c/include/hdds.h porte les mêmes déclarations avec un en-tête de licence, et c'est la copie installée.

Optionnel : installer l'en-tête, les deux bibliothèques, un fichier pkg-config et la configuration CMake dans un préfixe :

make install-c PREFIX=$HOME/.local     # PREFIX par défaut : /usr/local

Étape 1 : Configuration du projet​

Créez un répertoire de projet à côté du dépôt HDDS :

mkdir hdds-hello-c
cd hdds-hello-c

Étape 2 : Créer le Publisher​

Créez publisher.c :

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "hdds.h"

int main(void) {
// Line-buffer stdout so each line shows up at once, even through a pipe or a file
setvbuf(stdout, NULL, _IOLBF, 0);
printf("Starting publisher...\n");

// Initialize logging (optional)
hdds_logging_init(HDDS_LOG_WARN);

// Create participant with UDP multicast transport. No domain in code:
// the domain comes from the HDDS_DOMAIN_ID environment variable.
struct HddsParticipant *participant =
hdds_participant_create_with_transport("publisher", HDDS_TRANSPORT_UDP_MULTICAST);
if (participant == NULL) {
fprintf(stderr, "Failed to create participant\n");
return 1;
}
printf("Participant created: %s, domain %u\n",
hdds_participant_name(participant), hdds_participant_domain_id(participant));

// Create QoS profile (reliable, transient-local)
struct HddsQoS *qos = hdds_qos_reliable();
hdds_qos_set_transient_local(qos);
hdds_qos_set_history_depth(qos, 10);

// Create writer with QoS
struct HddsDataWriter *writer =
hdds_writer_create_with_qos(participant, "hello/world", qos);
if (writer == NULL) {
fprintf(stderr, "Failed to create writer\n");
hdds_qos_destroy(qos);
hdds_participant_destroy(participant);
return 1;
}
printf("Writer created on topic: hello/world\n");

// QoS no longer needed after writer creation
hdds_qos_destroy(qos);

// Wait until a subscriber is matched (10 s at most) before the first write
printf("Waiting for a subscriber...\n");
enum HddsError status = hdds_writer_wait_for_matched_readers(writer, 1, 10000);
if (status != HDDS_OK) {
fprintf(stderr, "No subscriber matched (error %d): see Network Prerequisites\n", status);
hdds_writer_destroy(writer);
hdds_participant_destroy(participant);
return 1;
}

// Publish messages (raw bytes)
int failed = 0;
for (int i = 0; i < 10; i++) {
char message[64];
int len = snprintf(message, sizeof(message), "Hello #%d from C!", i);

enum HddsError result = hdds_writer_write(writer, message, len);
if (result == HDDS_OK) {
printf("Published: %s\n", message);
} else {
fprintf(stderr, "Write failed: %d\n", result);
failed = 1;
}

sleep(1);
}

// Cleanup
printf("Cleaning up...\n");
hdds_writer_destroy(writer);
hdds_participant_destroy(participant);
printf("Done.\n");

return failed;
}

L'étape 2 attend un appariement volontairement : un échantillon écrit avant que l'abonné ne soit apparié n'est pas livré à un reader VOLATILE, si bien que les premières écritures dépendraient du temps de découverte.

Étape 3 : Créer le Subscriber​

Créez subscriber.c :

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include "hdds.h"

/* Stop after this many samples, or after this long without any sample. */
#define EXPECTED_SAMPLES 10
#define IDLE_TIMEOUT_NS (10LL * 1000 * 1000 * 1000)

int main(void) {
// Line-buffer stdout so each line shows up at once, even through a pipe or a file
setvbuf(stdout, NULL, _IOLBF, 0);
printf("Starting subscriber...\n");

// Initialize logging
hdds_logging_init(HDDS_LOG_WARN);

// Create participant with UDP multicast transport. No domain in code:
// the domain comes from the HDDS_DOMAIN_ID environment variable.
struct HddsParticipant *participant =
hdds_participant_create_with_transport("subscriber", HDDS_TRANSPORT_UDP_MULTICAST);
if (participant == NULL) {
fprintf(stderr, "Failed to create participant\n");
return 1;
}
printf("Participant created, domain %u\n", hdds_participant_domain_id(participant));

// Create QoS (must be compatible with writer)
struct HddsQoS *qos = hdds_qos_reliable();
hdds_qos_set_history_depth(qos, 100);

// Create reader with QoS
struct HddsDataReader *reader =
hdds_reader_create_with_qos(participant, "hello/world", qos);
if (reader == NULL) {
fprintf(stderr, "Failed to create reader\n");
hdds_qos_destroy(qos);
hdds_participant_destroy(participant);
return 1;
}
printf("Reader created on topic: hello/world\n");
hdds_qos_destroy(qos);

// Set up WaitSet for event-driven reading
struct HddsWaitSet *waitset = hdds_waitset_create();
const struct HddsStatusCondition *condition =
hdds_reader_get_status_condition(reader);
hdds_waitset_attach_status_condition(waitset, condition);

printf("Waiting for data...\n");

// Read loop: stops after EXPECTED_SAMPLES samples or after IDLE_TIMEOUT_NS of silence
char buffer[256];
size_t len_read;
const void *triggered[4];
size_t triggered_count;
int received = 0;

while (received < EXPECTED_SAMPLES) {
// hdds_waitset_wait returns HDDS_OK with triggered_count == 0 on timeout
enum HddsError wait_result = hdds_waitset_wait(
waitset, IDLE_TIMEOUT_NS, triggered, 4, &triggered_count);
if (wait_result != HDDS_OK || triggered_count == 0) {
printf("No data for 10 s, exiting\n");
break;
}

// Take all available samples
while (hdds_reader_take(reader, buffer, sizeof(buffer) - 1, &len_read) == HDDS_OK) {
buffer[len_read] = '\0';
printf("Received: %s\n", buffer);
received++;
}
}
printf("Received %d samples\n", received);

// Cleanup
hdds_waitset_detach_condition(waitset, condition);
hdds_status_condition_release(condition);
hdds_waitset_destroy(waitset);
hdds_reader_destroy(reader);
hdds_participant_destroy(participant);

return 0;
}

Étape 4 : Créer le Makefile​

Créez Makefile. Il lie la bibliothèque statique directement depuis le dépôt HDDS, si bien que les programmes s'exécutent sans configurer de chemin de bibliothèque :

# Path to your HDDS checkout
HDDS ?= ../hdds

CC = gcc
CFLAGS = -Wall -Wextra -O2 -I$(HDDS)/sdk/c/include
LDLIBS = $(HDDS)/target/release/libhdds_c.a -lpthread -ldl -lm

all: publisher subscriber

publisher: publisher.c
$(CC) $(CFLAGS) -o $@ $< $(LDLIBS)

subscriber: subscriber.c
$(CC) $(CFLAGS) -o $@ $< $(LDLIBS)

clean:
rm -f publisher subscriber

.PHONY: all clean

Bibliothèque partagée. -lhdds_c choisit libhdds_c.so quand elle existe, et le programme doit alors la trouver à l'exécution :

gcc -I../hdds/sdk/c/include publisher.c -L../hdds/target/release -lhdds_c -o publisher
LD_LIBRARY_PATH=../hdds/target/release ./publisher

Sans LD_LIBRARY_PATH (ou une installation dans un répertoire connu du chargeur, suivie de ldconfig), le programme s'arrête sur error while loading shared libraries: libhdds_c.so: cannot open shared object file: No such file or directory.

pkg-config, après make install-c PREFIX=$HOME/.local :

export PKG_CONFIG_PATH=$HOME/.local/lib/pkgconfig
gcc publisher.c $(pkg-config --cflags --libs hdds_c) -o publisher # shared
gcc publisher.c $(pkg-config --cflags hdds_c) $HOME/.local/lib/libhdds_c.a -lpthread -ldl -lm -o publisher # static

CMake, depuis le dépôt ou un préfixe d'installation (le composant C n'a pas besoin du SDK C++) :

cmake_minimum_required(VERSION 3.16)
project(hello_c C)
find_package(hdds REQUIRED COMPONENTS c)
add_executable(publisher publisher.c)
target_link_libraries(publisher PRIVATE hdds::hdds_c) # static libhdds_c.a
cmake -B build -DCMAKE_PREFIX_PATH=/path/to/hdds/sdk/cmake    # or =$HOME/.local
cmake --build build

make test-c-install, dans le dépôt HDDS, compile et exécute un programme de chacune de ces façons contre un préfixe d'installation temporaire.

Étape 5 : Compiler et exécuter​

Les deux programmes prennent leur domaine DDS dans la variable d'environnement HDDS_DOMAIN_ID (voir variables d'environnement). Exportez la même valeur dans les deux terminaux (toute valeur de 0 à 232) :

# Build
make

# Terminal 1 - Start subscriber
export HDDS_DOMAIN_ID=42
./subscriber

# Terminal 2 - Start publisher
export HDDS_DOMAIN_ID=42
./publisher

L'abonné s'arrête après 10 échantillons, ou après 10 s sans échantillon. Le publisher attend jusqu'à 10 s un abonné, puis écrit 10 échantillons.

Sortie attendue​

Subscriber :

Starting subscriber...
Participant created, domain 42
Reader created on topic: hello/world
Waiting for data...
Received: Hello #0 from C!
Received: Hello #1 from C!
Received: Hello #2 from C!
...
Received: Hello #9 from C!
Received 10 samples

Publisher :

Starting publisher...
Participant created: publisher, domain 42
Writer created on topic: hello/world
Waiting for a subscriber...
Published: Hello #0 from C!
Published: Hello #1 from C!
...
Published: Hello #9 from C!
Cleaning up...
Done.

L'abonné affiche No data for 10 s, exiting au lieu de Received 10 samples lorsque le publisher s'arrête tôt ou ne s'apparie jamais. Le publisher affiche No subscriber matched (error 24): see Network Prerequisites et sort avec le code 1 si aucun abonné ne s'apparie dans les 10 s.

Référence API C​

Participant​

// Explicit domain (wins over HDDS_DOMAIN_ID); hdds_config_build consumes config
struct HddsParticipantConfig *config = hdds_config_create("my_app");
hdds_config_set_domain_id(config, 42);
hdds_config_set_transport_mode(config, HDDS_TRANSPORT_UDP_MULTICAST); // or HDDS_TRANSPORT_INTRA_PROCESS
struct HddsParticipant *p = hdds_config_build(config);

// Properties
const char *name = hdds_participant_name(p);
uint32_t domain = hdds_participant_domain_id(p);

// Cleanup
hdds_participant_destroy(p);
// No domain in code: HDDS_DOMAIN_ID picks it (see environment variables)
struct HddsParticipant *p = hdds_participant_create_with_transport(
"my_app",
HDDS_TRANSPORT_UDP_MULTICAST // or HDDS_TRANSPORT_INTRA_PROCESS
);
hdds_participant_destroy(p);

Writer​

// Create with default QoS
struct HddsDataWriter *w = hdds_writer_create(participant, "topic_name");

// Create with custom QoS
struct HddsDataWriter *w = hdds_writer_create_with_qos(participant, "topic_name", qos);

// Write raw bytes
enum HddsError result = hdds_writer_write(writer, data_ptr, data_len);

// Number of matched readers (0 until discovery matched one)
uint32_t matched;
hdds_writer_matched_reader_count(writer, &matched);

// Cleanup
hdds_writer_destroy(w);

Un writer créé avec hdds_writer_create() marque ses échantillons FINAL. Pour un DataWriter typé, utilisez le constructeur généré par hddsgen (voir la section « Utilisation avec des données typées »).

Reader​

// Create with custom QoS (default QoS: hdds_reader_create(participant, "topic_name"))
struct HddsDataReader *r = hdds_reader_create_with_qos(participant, "topic_name", qos);

// Take data (removes from cache)
char buffer[1024];
size_t len_out;
if (hdds_reader_take(r, buffer, sizeof(buffer), &len_out) == HDDS_OK) {
printf("Received %zu bytes\n", len_out);
}

// Cleanup
hdds_reader_destroy(r);

hdds_reader_take renvoie HDDS_NOT_FOUND quand aucun échantillon n'est disponible. Dimensionnez le buffer pour l'échantillon : une lecture qui ne peut pas copier l'échantillon renvoie un code non HDDS_OK.

QoS​

Un writer et un reader ne s'apparient que si le writer offre au moins ce que le reader demande (voir compatibilité QoS).

// Create QoS profiles
struct HddsQoS *qos = hdds_qos_default(); // Best effort, volatile
struct HddsQoS *qos = hdds_qos_best_effort(); // Explicit best effort
struct HddsQoS *qos = hdds_qos_reliable(); // Reliable delivery

// Configure QoS
hdds_qos_set_history_depth(qos, 10);
hdds_qos_set_history_keep_all(qos);
hdds_qos_set_transient_local(qos);
hdds_qos_set_volatile(qos);
hdds_qos_set_reliable(qos);
hdds_qos_set_best_effort(qos);
hdds_qos_set_deadline_ns(qos, 100000000); // 100ms

// Load from XML
struct HddsQoS *qos = hdds_qos_from_xml("/path/to/profile.xml");

// Cleanup
hdds_qos_destroy(qos);

WaitSet​

// Create waitset
struct HddsWaitSet *ws = hdds_waitset_create();

// Get reader's status condition
const struct HddsStatusCondition *cond = hdds_reader_get_status_condition(reader);

// Attach condition
hdds_waitset_attach_status_condition(ws, cond);

// Wait for events
const void *triggered[10];
size_t count;
int64_t timeout_ns = 1000000000; // 1 second
enum HddsError result = hdds_waitset_wait(ws, timeout_ns, triggered, 10, &count);

// Cleanup
hdds_waitset_detach_condition(ws, cond);
hdds_status_condition_release(cond);
hdds_waitset_destroy(ws);

Codes d'erreur​

La plupart des fonctions renvoient un HddsError ; les constructeurs renvoient NULL à la place. Le tableau est celui de la Référence API C :

NameValueMeaning (hdds.h)
HDDS_OK0Success
HDDS_INVALID_ARGUMENT1Invalid argument provided (null pointer, invalid value)
HDDS_NOT_FOUND2Requested resource not found
HDDS_OPERATION_FAILED3Generic operation failure
HDDS_OUT_OF_MEMORY4Memory allocation failed
HDDS_CONFIG_ERROR10Invalid configuration settings
HDDS_INVALID_DOMAIN_ID11Invalid domain ID (must be 0-232)
HDDS_INVALID_PARTICIPANT_ID12Invalid participant ID (must be 0-119)
HDDS_NO_AVAILABLE_PARTICIPANT_ID13No available participant ID (all 120 ports occupied)
HDDS_INVALID_STATE14Invalid entity state for requested operation
HDDS_IO_ERROR20Generic I/O error
HDDS_TRANSPORT_ERROR21UDP transport send/receive failed
HDDS_REGISTRATION_FAILED22Topic registration failed
HDDS_WOULD_BLOCK23Operation would block but non-blocking mode requested
HDDS_TIMEOUT24Operation did not complete before the requested timeout
HDDS_TYPE_MISMATCH30Type mismatch between writer and reader
HDDS_SERIALIZATION_ERROR31CDR serialization failed
HDDS_BUFFER_TOO_SMALL32Buffer too small for encoding
HDDS_ENDIAN_MISMATCH33CDR endianness mismatch
HDDS_QOS_INCOMPATIBLE40QoS policies are incompatible between endpoints
HDDS_UNSUPPORTED41Requested feature or operation is not supported
HDDS_PERMISSION_DENIED50Permission denied by access control (DDS Security)
HDDS_AUTHENTICATION_FAILED51Authentication failed

Les constructeurs (hdds_participant_create, hdds_writer_create_with_qos, ...) renvoient NULL en cas d'échec ; la raison est écrite dans le journal HDDS (activé par hdds_logging_init), par exemple une QoS incohérente comme une profondeur d'historique supérieure à max_samples_per_instance.

Logging​

// Initialize with level
hdds_logging_init(HDDS_LOG_INFO); // HDDS_LOG_OFF, HDDS_LOG_ERROR, HDDS_LOG_WARN, HDDS_LOG_INFO, HDDS_LOG_DEBUG, HDDS_LOG_TRACE

// Or with environment variable (RUST_LOG)
hdds_logging_init_env(HDDS_LOG_INFO);

// Or with filter string
hdds_logging_init_with_filter("hdds=debug");

Utilisation avec des données typées (hdds_gen)​

Pour des données typées, utilisez hdds_gen pour générer des structs C et des fonctions de sérialisation CDR2 :

Étape 1 : Définir le fichier IDL​

Créez temperature.idl :

struct Temperature {
uint32 sensor_id;
float value;
string unit;
};

Étape 2 : Générer le code C​

hddsgen gen c temperature.idl -o temperature.h     # hddsgen 2.0 ou plus récent

hddsgen gen --help liste les cibles et les options. Installation de hddsgen : hdds_gen Installation.

Cela génère un fichier header-only avec :

  • la struct C Temperature (unit est un char *)
  • temperature_encode_cdr2_le() et temperature_decode_cdr2_le_alloc() (plus temperature_decode_cdr2_le() pour les types sans chaînes ni séquences)
  • temperature_create_writer(), le constructeur typé du DataWriter

Temperature n'a pas d'annotation d'extensibilité : hddsgen le génère donc APPENDABLE (valeur par défaut depuis hddsgen 2.0, DDS-XTypes 1.3 7.3.1.2.1.8) et affiche une ligne d'information à ce sujet. Writers et readers doivent s'accorder sur l'extensibilité : créez donc les writers avec temperature_create_writer(), qui marque chaque échantillon APPENDABLE, contrairement à hdds_writer_create() qui marque toujours FINAL. Pour obtenir la disposition de hddsgen 1.x et antérieur, générez avec --default-extensibility final, ou annotez le type.

Pour un type avec des membres @key (instances, dispose, unregister_instance), voir Types à clé.

Étape 3 : Publisher avec le code généré​

Créez typed_publisher.c :

#include <stdio.h>
#include <unistd.h>
#include "temperature.h"
#include "hdds.h"

int main(void) {
hdds_logging_init(HDDS_LOG_WARN);

// No domain in code: the domain comes from the HDDS_DOMAIN_ID environment variable
struct HddsParticipant *participant =
hdds_participant_create_with_transport("sensor", HDDS_TRANSPORT_UDP_MULTICAST);
if (participant == NULL) {
fprintf(stderr, "Failed to create participant\n");
return 1;
}

struct HddsQoS *qos = hdds_qos_reliable();
hdds_qos_set_history_depth(qos, 10);
struct HddsDataWriter *writer =
temperature_create_writer(participant, "sensors/temperature", qos);
hdds_qos_destroy(qos);
if (writer == NULL) {
fprintf(stderr, "Failed to create writer\n");
hdds_participant_destroy(participant);
return 1;
}

// Wait until a subscriber is matched (10 s at most) before the first write
enum HddsError status = hdds_writer_wait_for_matched_readers(writer, 1, 10000);
if (status != HDDS_OK) {
fprintf(stderr, "No subscriber matched (error %d): see Network Prerequisites\n", status);
hdds_writer_destroy(writer);
hdds_participant_destroy(participant);
return 1;
}

int failed = 0;
for (uint32_t i = 0; i < 10; i++) {
Temperature temp = {0};
temp.sensor_id = 42;
temp.value = 23.5f + (float)i;
temp.unit = "celsius";

// Encode to CDR2 bytes: the byte count on success, a negative CDR_* code on failure
uint8_t buffer[256];
int encoded_len = temperature_encode_cdr2_le(&temp, buffer, sizeof(buffer));
if (encoded_len < 0) {
fprintf(stderr, "Encode failed: %d\n", encoded_len);
failed = 1;
break;
}
if (hdds_writer_write(writer, buffer, (size_t)encoded_len) != HDDS_OK) {
fprintf(stderr, "Write failed\n");
failed = 1;
} else {
printf("Published: sensor %u, %.1f %s\n", temp.sensor_id, temp.value, temp.unit);
}
sleep(1);
}

hdds_writer_destroy(writer);
hdds_participant_destroy(participant);
return failed;
}

Étape 4 : Subscriber avec le code généré​

Créez typed_subscriber.c :

#include <stdio.h>
#include "temperature.h"
#include "hdds.h"

/* Stop after this many samples, or after this long without any sample. */
#define EXPECTED_SAMPLES 10
#define IDLE_TIMEOUT_NS (10LL * 1000 * 1000 * 1000)

int main(void) {
hdds_logging_init(HDDS_LOG_WARN);

// No domain in code: the domain comes from the HDDS_DOMAIN_ID environment variable
struct HddsParticipant *participant =
hdds_participant_create_with_transport("sensor_display", HDDS_TRANSPORT_UDP_MULTICAST);
if (participant == NULL) {
fprintf(stderr, "Failed to create participant\n");
return 1;
}

struct HddsQoS *qos = hdds_qos_reliable();
hdds_qos_set_history_depth(qos, 100);
struct HddsDataReader *reader =
hdds_reader_create_with_type(participant, "sensors/temperature", "Temperature", qos);
hdds_qos_destroy(qos);
if (reader == NULL) {
fprintf(stderr, "Failed to create reader\n");
hdds_participant_destroy(participant);
return 1;
}

struct HddsWaitSet *waitset = hdds_waitset_create();
const struct HddsStatusCondition *condition = hdds_reader_get_status_condition(reader);
hdds_waitset_attach_status_condition(waitset, condition);

// Storage for the decoded string field: a bump arena over a buffer we own
static uint8_t storage[256];
hdds_x2c_arena arena;
hdds_x2c_arena_init(&arena, storage, sizeof(storage));

uint8_t buffer[256];
size_t len_read;
const void *triggered[4];
size_t triggered_count;
int received = 0;

while (received < EXPECTED_SAMPLES) {
// hdds_waitset_wait returns HDDS_OK with triggered_count == 0 on timeout
enum HddsError wait_result = hdds_waitset_wait(
waitset, IDLE_TIMEOUT_NS, triggered, 4, &triggered_count);
if (wait_result != HDDS_OK || triggered_count == 0) {
printf("No data for 10 s, exiting\n");
break;
}

while (hdds_reader_take(reader, buffer, sizeof(buffer), &len_read) == HDDS_OK) {
arena.used = 0; // reuse the storage for each sample
Temperature temp = {0};
int decoded = temperature_decode_cdr2_le_alloc(
&temp, buffer, len_read, hdds_x2c_arena_alloc, &arena);
if (decoded < 0) {
fprintf(stderr, "Decode failed: %d\n", decoded);
continue;
}
printf("Sensor %u: %.1f %s\n", temp.sensor_id, temp.value, temp.unit);
received++;
}
}
printf("Received %d samples\n", received);

hdds_waitset_detach_condition(waitset, condition);
hdds_status_condition_release(condition);
hdds_waitset_destroy(waitset);
hdds_reader_destroy(reader);
hdds_participant_destroy(participant);
return 0;
}

Compilez les deux (temperature.h doit se trouver dans le même répertoire) :

for p in typed_publisher typed_subscriber; do
gcc -Wall -Wextra -O2 -I../hdds/sdk/c/include $p.c \
../hdds/target/release/libhdds_c.a -lpthread -ldl -lm -o $p
done

Lancez-les comme à l'étape 5, avec le même HDDS_DOMAIN_ID dans les deux terminaux.

L'abonné crée son reader avec hdds_reader_create_with_type() et le nom de type Temperature, le nom qu'annonce le writer généré. Un reader créé avec hdds_reader_create_with_qos() annonce à la place un nom de type générique, et HDDS journalise un avertissement signalant que les deux noms diffèrent.

Les champs string ont besoin d'un allocateur

Le décodeur généré n'alloue pas de mémoire tout seul. Un champ string (ici unit) est stocké dans une mémoire fournie au décodeur : passez un callback d'allocation, comme temperature_decode_cdr2_le_alloc(..., hdds_x2c_arena_alloc, &arena). hdds_x2c_arena est un allocateur bump sur un buffer que vous possédez ; remettez arena.used à 0 pour le réutiliser. Décoder un type avec un champ string sans allocateur (temperature_decode_cdr2_le()) échoue avec -CDR_OUT_OF_MEMORY (-4).

Codes de retour des fonctions générées​

  • L'encodage (*_encode_cdr2_le) renvoie le nombre d'octets écrits ; le décodage (*_decode_cdr2_le*) renvoie le nombre d'octets lus.
  • En cas d'échec, les deux renvoient un code négatif du header généré, l'opposé de la constante CDR_* : -CDR_INVALID_DATA (-1), -CDR_UNEXPECTED_EOF (-2), -CDR_BUFFER_TOO_SMALL (-3), -CDR_OUT_OF_MEMORY (-4).
  • Testez < 0, pas == 0 : une valeur de retour positive est une longueur, jamais une erreur.

Dépannage : l'abonné ne reçoit rien​

  • No data for 10 s, exiting et Received 0 samples ? Rien n'est arrivé, l'abonné abandonne au bout de 10 s. Vérifiez que le publisher tourne avec le même HDDS_DOMAIN_ID et le même topic. Un publisher qui ne s'apparie jamais affiche No subscriber matched (error 24) et sort avec le code 1. La découverte peut en être la cause : sur une seule machine, lancez les deux programmes avec HDDS_INTERFACE=lo. Cherchez IP_MULTICAST_IF=... blocked (VPN/tunnel policy?) dans le journal. Côté publisher, hdds_writer_matched_reader_count() indique si l'abonné a été trouvé. Guide complet : Prérequis réseau.
  • Aucune sortie quand elle est redirigée vers un fichier ou un tube ? stdio met stdout en tampon quand ce n'est pas un terminal ; les exemples ci-dessus appellent setvbuf(stdout, NULL, _IOLBF, 0) pour cette raison.
  • Même domaine et même topic ? Réglez HDDS_DOMAIN_ID à la même valeur dans les deux terminaux (voir variables d'environnement). Le nom du topic doit aussi être identique.

Prochaines étapes​