blob: 18acaa9e1e116a702b64fba74d6be57352244e8b [file] [log] [blame]
Kyle Stachowicz4addac62017-12-02 23:12:34 -08001#include "aos/common/message.h"
brians343bc112013-02-10 01:53:46 +00002
Brian4a424a22014-04-02 11:52:45 -07003#include <inttypes.h>
Austin Schuhf2a50ba2016-12-24 16:16:26 -08004#include <chrono>
5
6#include "aos/common/byteorder.h"
brians343bc112013-02-10 01:53:46 +00007
8namespace aos {
9
Austin Schuhf2a50ba2016-12-24 16:16:26 -080010namespace chrono = ::std::chrono;
11
12void Message::Zero() { sent_time = monotonic_clock::min_time; }
brians343bc112013-02-10 01:53:46 +000013
14size_t Message::Deserialize(const char *buffer) {
15 int32_t sec;
Austin Schuhf907f2e2018-01-02 01:15:27 -080016 uint32_t nsec;
brians343bc112013-02-10 01:53:46 +000017 to_host(&buffer[0], &sec);
18 to_host(&buffer[4], &nsec);
Austin Schuhf2a50ba2016-12-24 16:16:26 -080019 sent_time = monotonic_clock::time_point(chrono::seconds(sec) +
20 chrono::nanoseconds(nsec));
brians343bc112013-02-10 01:53:46 +000021 return Size();
22}
23// Serializes the common fields into the buffer.
24size_t Message::Serialize(char *buffer) const {
25 // TODO(aschuh): to_network shouldn't need a pointer.
Austin Schuhf2a50ba2016-12-24 16:16:26 -080026 int32_t sec =
27 chrono::duration_cast<chrono::seconds>(sent_time.time_since_epoch())
28 .count();
Austin Schuhf907f2e2018-01-02 01:15:27 -080029 uint32_t nsec = chrono::duration_cast<chrono::nanoseconds>(
30 sent_time.time_since_epoch() - chrono::seconds(sec))
31 .count();
brians343bc112013-02-10 01:53:46 +000032 to_network(&sec, &buffer[0]);
33 to_network(&nsec, &buffer[4]);
34 return Size();
35}
36
37size_t Message::Print(char *buffer, int length) const {
Austin Schuhf2a50ba2016-12-24 16:16:26 -080038 int32_t sec =
39 chrono::duration_cast<chrono::seconds>(sent_time.time_since_epoch())
40 .count();
Austin Schuhf907f2e2018-01-02 01:15:27 -080041 uint32_t nsec = chrono::duration_cast<chrono::nanoseconds>(
42 sent_time.time_since_epoch() - chrono::seconds(sec))
43 .count();
44 return snprintf(buffer, length, "%" PRId32 ".%09" PRIu32 "s", sec, nsec);
brians343bc112013-02-10 01:53:46 +000045}
46
47} // namespace aos