Build: add GCC-13, Clang-14, Clang-15, Clang-16, Clang-17
[marnav.git] / examples / read_seatalk.cpp
blobd7af1eada11f6ece95873a5e11144c629c24a18d
1 #include <marnav-io/seatalk_reader.hpp>
2 #include <marnav-io/default_seatalk_serial.hpp>
3 #include <marnav/seatalk/seatalk.hpp>
4 #include <marnav/seatalk/message_00.hpp>
5 #include <iostream>
7 using namespace marnav;
9 /// Works only in a single threaded context (true for serial and seatalk_reader).
10 ///
11 /// This class is implemented inline, for easier handling within this example.
12 class message_reader : public io::seatalk_reader
14 public:
15 message_reader(std::unique_ptr<io::device> && dev)
16 : seatalk_reader(std::move(dev))
20 ~message_reader() override = default;
22 /// Reads synchronously messages from the device.
23 ///
24 /// @param[out] data The received message.
25 /// @retval true Success.
26 /// @retval false End of file.
27 /// @exception std::runtime_error
28 bool read_message(seatalk::raw & data)
30 // reads as long as the message is not complete.
31 while (read()) {
32 // the message was received, return it and reset the 'semaphore'.
33 // please note: this works only in single threaded environment,
34 // since the 'semaphore' isn't really one.
35 if (message_received) {
36 data = message_;
37 message_received = false;
38 return true;
41 return false;
44 protected:
45 /// Processes the received message. Uses the data member 'message_received'
46 /// as poor-mans semaphore to signal the receipt.
47 ///
48 /// After the reception, the message will be stored temporarily.
49 void process_message(const seatalk::raw & msg) override
51 message_ = msg;
52 message_received = true;
55 private:
56 bool message_received{false};
57 seatalk::raw message_;
60 int main(int, char **)
62 using namespace marnav::io;
64 // create and open the device for reading.
65 message_reader reader{make_default_seatalk_serial("/dev/ttyUSB0")};
67 seatalk::raw data;
69 // read and process SeaTalk messages, bus synchronization is done automatically.
70 while (reader.read_message(data)) {
71 // data was successfully read from the SeaTalk bus, inclusive synchronization
72 // of SeaTalk messages. This means it is possible to begin to listen on the
73 // bus at any time.
74 auto msg = seatalk::make_message(data);
76 // do something with the message, for example dump the depth and ignore all
77 // other messages.
78 if (msg->type() == seatalk::message_id::depth_below_transducer) {
79 auto depth = seatalk::message_cast<seatalk::message_00>(msg);
80 std::cout << "depth below transducer: " << depth->get_depth() << "\n";