@@ -27,6 +27,14 @@ std::string random_string( size_t length )
2727 return str;
2828}
2929
30+ int64_t millis_monotonic (void )
31+ {
32+ struct timespec spec;
33+ clock_gettime (CLOCK_MONOTONIC, &spec);
34+ const int64_t ms = (spec.tv_sec *1000 ) + round (spec.tv_nsec / 1.0e6 );
35+ return ms;
36+ }
37+
3038std::string string_to_upper_copy (const std::string &str) {
3139 std::string ret;
3240 ret.resize (str.size ());
@@ -315,8 +323,12 @@ class MosquittoEngine final : public Engine, protected mqtt_event_listener, prot
315323
316324public:
317325 MosquittoEngine (const EngineConfig config, const string &host, const int port,
318- const int keep_alive, const string &client_id, const bool clean_session) :
319- _debugOutput (config.debugOutput()), client(this , host, port, keep_alive, client_id, clean_session) {
326+ const int keep_alive, const string &client_id, const bool clean_session)
327+ : _debugOutput(config.debugOutput())
328+ , client(this , host, port, keep_alive, client_id, clean_session)
329+ , discoveryLastSent(0 )
330+ , discoveryPeriod(config.discoveryPeriod/3 )
331+ {
320332 client.connect ();
321333 }
322334
@@ -343,6 +355,14 @@ class MosquittoEngine final : public Engine, protected mqtt_event_listener, prot
343355 run = true ;
344356
345357 while (run) {
358+ const auto t = millis_monotonic ()/1000 ;
359+ if (connected and (t - discoveryLastSent) > discoveryPeriod) {
360+ for (auto &r: registrations) {
361+ sendDiscoveryMessage (r);
362+ }
363+ discoveryLastSent = t;
364+ }
365+
346366 client.poll ();
347367 }
348368 }
@@ -374,22 +394,31 @@ class MosquittoEngine final : public Engine, protected mqtt_event_listener, prot
374394 }
375395
376396 virtual void on_connect (int rc) override {
397+ connected = true ;
377398 for (auto &r: registrations) {
378399 for (auto &p : r.inports ) {
379400 on_msg (" Connecting port " + p.id + " to mqtt topic " + p.queue );
380401 client.subscribe (nullptr , p.queue , 0 );
381402 }
382-
383- string data = json11::Json (r.discoveryMessage ).dump ();
384- client.publish (nullptr , " fbp" , 0 , false , data);
403+ sendDiscoveryMessage (r);
385404 }
405+ discoveryLastSent = millis_monotonic ()/1000 ;
406+ }
407+
408+ private:
409+ void sendDiscoveryMessage (const ParticipantRegistration &r) {
410+ const string data = json11::Json (r.discoveryMessage ).dump ();
411+ client.publish (nullptr , " fbp" , 0 , false , data);
386412 }
387413
388414private:
389415 const bool _debugOutput;
390416 atomic_bool run;
391417 msg_flo_mqtt_client client;
392418 vector<ParticipantRegistration> registrations;
419+ bool connected;
420+ int64_t discoveryLastSent;
421+ const int64_t discoveryPeriod;
393422};
394423
395424shared_ptr<Engine> createEngine (const EngineConfig config) {
0 commit comments