16 void set_sync_flag(struct sync_flag *s, bool value) {
17 pthread_mutex_lock(&s->mutex);
19 pthread_cond_broadcast(&s->cond);
20 pthread_mutex_unlock(&s->mutex);
23 bool check_sync_flag(struct sync_flag *s) {
25 pthread_mutex_lock(&s->mutex);
27 pthread_mutex_unlock(&s->mutex);
31 bool wait_sync_flag(struct sync_flag *s, int seconds) {
32 struct timespec timeout;
33 clock_gettime(CLOCK_REALTIME, &timeout);
34 timeout.tv_sec += seconds;
36 pthread_mutex_lock(&s->mutex);
39 if(!pthread_cond_timedwait(&s->cond, &s->mutex, &timeout) || errno != EINTR) {
44 pthread_mutex_unlock(&s->mutex);
49 void link_meshlink_pair(meshlink_handle_t *a, meshlink_handle_t *b) {
50 // Import and export both side's data
52 assert(meshlink_set_canonical_address(a, meshlink_get_self(a), "localhost", NULL));
53 assert(meshlink_set_canonical_address(b, meshlink_get_self(b), "localhost", NULL));
55 char *data = meshlink_export(a);
57 assert(meshlink_import(b, data));
60 data = meshlink_export(b);
62 assert(meshlink_import(a, data));
66 void open_meshlink_pair(meshlink_handle_t **pa, meshlink_handle_t **pb, const char *prefix) {
67 // Create two new MeshLink instances
71 char *a_name, *b_name;
73 assert(asprintf(&a_name, "%s_conf.1", prefix) > 0);
76 assert(asprintf(&b_name, "%s_conf.2", prefix) > 0);
79 assert(meshlink_destroy(a_name));
80 assert(meshlink_destroy(b_name));
82 meshlink_handle_t *a = meshlink_open(a_name, "a", prefix, DEV_CLASS_BACKBONE);
85 meshlink_handle_t *b = meshlink_open(b_name, "b", prefix, DEV_CLASS_BACKBONE);
91 meshlink_enable_discovery(a, false);
92 meshlink_enable_discovery(b, false);
94 link_meshlink_pair(a, b);
100 // Don't poll in the application thread, use a condition variable to signal when the peer is online.
101 static void pair_status_cb(meshlink_handle_t *mesh, meshlink_node_t *node, bool reachable) {
105 set_sync_flag(mesh->priv, true);
109 void start_meshlink_pair(meshlink_handle_t *a, meshlink_handle_t *b) {
110 struct sync_flag pair_status = {.flag = false};
112 a->priv = &pair_status;
113 meshlink_set_node_status_cb(a, pair_status_cb);
115 assert(meshlink_start(a));
116 assert(meshlink_start(b));
118 assert(wait_sync_flag(&pair_status, 5));
120 meshlink_set_node_status_cb(a, NULL);
124 void stop_meshlink_pair(meshlink_handle_t *a, meshlink_handle_t *b) {
129 void close_meshlink_pair(meshlink_handle_t *a, meshlink_handle_t *b) {
134 void log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, const char *text) {
135 static const char *levelstr[] = {
136 [MESHLINK_DEBUG] = "DEBUG",
137 [MESHLINK_INFO] = "INFO",
138 [MESHLINK_WARNING] = "WARNING",
139 [MESHLINK_ERROR] = "ERROR",
140 [MESHLINK_CRITICAL] = "CRITICAL",
143 static struct timespec ts0;
146 clock_gettime(CLOCK_MONOTONIC, &ts);
148 if(ts0.tv_sec == 0) {
152 float diff = (ts.tv_sec - ts0.tv_sec) + (ts.tv_nsec - ts0.tv_nsec) * 1e-9;
154 fprintf(stderr, "%7.3f (%s) [%s] %s\n",
156 mesh ? mesh->name : "",