I want to recover an MQTT message publish timestamp but I couldn't find Support in the subscriber library. In the other hand I see MQTT.fx client is able to recover this Information. Anyone knows how to handle that?
3 Answers
There is no timestamp in the message, there is no where to store such information in the MQTT v3 header.
MQTT.fx must be using time of arrival at the client.
If you need a published time you will have to add it to the message payload yourself.
-
I heard that in version 5 of the protocol you can add the timestamp as a property– sezanzebCommented Apr 6, 2022 at 8:19
-
3As mentioned in one of the other answers MQTT v5 does allow for setting arbitrary properties on messages, but that does still rely on coordination between the publisher ( or the broker in the case of the plugin) and the subscriber as to the name and format of the property, there is no explicit timestamp in the protocol– hardillbCommented Apr 6, 2022 at 8:25
In Eclipse Mosquitto, they have added a plugin to support having the broker timestamp the message in the user properties (MQQTv5 only): plugins/message-timestamp
Plugin code from: https://github.com/eclipse/mosquitto/blob/master/plugins/message-timestamp/mosquitto_message_timestamp.c
static int callback_message(int event, void *event_data, void *userdata)
{
struct mosquitto_evt_message *ed = event_data;
struct timespec ts;
struct tm *ti;
char time_buf[25];
clock_gettime(CLOCK_REALTIME, &ts);
ti = gmtime(&ts.tv_sec);
strftime(time_buf, sizeof(time_buf), "%Y-%m-%dT%H:%M:%SZ", ti);
return mosquitto_property_add_string_pair(&ed->properties, MQTT_PROP_USER_PROPERTY, "timestamp", time_buf);
}
User properties are not backwards compatible to MQTTv3. If you're stuck on MQTTv3, then you can:
- Add timestamps to your message payload (ugly because publisher timestamp might not be valid and adds complexity to payload)
- Avoid using retain (creates the need to timestamp and cache data at subscriber).
While Paho supports MQTTv5, some language variants do not. And some common debug tools like MQTT Explorer which do support MQTTv5 don't yet handle/display user properties.
-
1You've not said which MQTT broker has this plugin. Also the Paho Python client does support MQTTv5 (the Paho website just needs updating)– hardillbCommented Jan 14, 2021 at 14:26
-
1
You can use custom format string
example:
mosquitto_sub -v -t "your topic" -F "%I %t %p"
For more details: Click here
-
1