AIS: message 17 added.
[marnav.git] / examples / read_seatalk.cpp
blob6fe79074fe41b6aa1eb04d9d24d38f1ea87b4966
1 #include <iostream>
2 #include <marnav/io/seatalk_reader.hpp>
3 #include <marnav/io/default_seatalk_serial.hpp>
4 #include <marnav/seatalk/seatalk.hpp>
5 #include <marnav/seatalk/message_00.hpp>
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))
17 , message_received(false)
21 virtual ~message_reader() {}
23 /// Reads synchronously messages from the device.
24 ///
25 /// @param[out] data The received message.
26 /// @retval true Success.
27 /// @retval false End of file.
28 /// @exception std::runtime_error
29 bool read_message(seatalk::raw & data)
31 // reads as long as the message is not complete.
32 while (read()) {
33 // the message was received, return it and reset the 'semaphore'.
34 // please note: this works only in single threaded environment,
35 // since the 'semaphore' isn't really one.
36 if (message_received) {
37 data = message;
38 message_received = false;
39 return true;
42 return false;
45 protected:
46 /// Processes the received message. Uses the data member 'message_received'
47 /// as poor-mans semaphore to signal the receipt.
48 ///
49 /// After the reception, the message will be stored temporarily.
50 virtual void process_message(const seatalk::raw & msg) override
52 message = msg;
53 message_received = true;
56 private:
57 bool message_received;
58 seatalk::raw message;
61 int main(int, char **)
63 using namespace marnav::io;
65 // create and open the device for reading.
66 message_reader reader{make_default_seatalk_serial("/dev/ttyUSB0")};
68 seatalk::raw data;
70 // read and process SeaTalk messages, bus synchronization is done automatically.
71 while (reader.read_message(data)) {
72 // data was successfully read from the SeaTalk bus, inclusive synchronization
73 // of SeaTalk messages. This means it is possible to begin to listen on the
74 // bus at any time.
75 auto msg = seatalk::make_message(data);
77 // do something with the message, for example dump the depth and ignore all
78 // other messages.
79 if (msg->type() == seatalk::message_id::depth_below_transducer) {
80 auto depth = seatalk::message_cast<seatalk::message_00>(msg);
81 std::cout << "depth below transducer: " << depth->get_depth() << "\n";