|
| 1 | +#pragma once |
| 2 | + |
| 3 | +#include <stddef.h> |
| 4 | +#include <stdint.h> |
| 5 | + |
| 6 | +#include <ship_data_model.hpp> |
| 7 | + |
| 8 | +#include "seatalk/seatalk_apply.hpp" |
| 9 | +#include "seatalk/seatalk_frame.hpp" |
| 10 | + |
| 11 | +namespace seatalk { |
| 12 | + |
| 13 | +template<typename Real = float> |
| 14 | +class SeaTalkReceiver { |
| 15 | +public: |
| 16 | + const SeaTalkRxState& state() const { return state_; } |
| 17 | + const SeaTalkDecoded<Real>& last_decoded() const { return last_decoded_; } |
| 18 | + uint32_t decoded_count() const { return decoded_count_; } |
| 19 | + uint32_t unsupported_count() const { return unsupported_count_; } |
| 20 | + uint32_t bad_frame_count() const { return state_.bad_frame_count; } |
| 21 | + |
| 22 | + bool accept_datagram(const uint8_t* bytes, |
| 23 | + size_t length, |
| 24 | + ship_data_model::DataModel<Real>& model, |
| 25 | + uint64_t now_us, |
| 26 | + ship_data_model::SensorSource source) { |
| 27 | + SeaTalkFrame frame; |
| 28 | + if (!seatalk_frame_from_bytes(bytes, length, frame)) { |
| 29 | + ++state_.bad_frame_count; |
| 30 | + return false; |
| 31 | + } |
| 32 | + return apply_frame(frame, model, now_us, source); |
| 33 | + } |
| 34 | + |
| 35 | + bool accept_octet(uint8_t byte, |
| 36 | + ship_data_model::DataModel<Real>& model, |
| 37 | + uint64_t now_us, |
| 38 | + ship_data_model::SensorSource source) { |
| 39 | + SeaTalkFrame frame; |
| 40 | + if (!state_.feed_byte(byte, frame)) return true; |
| 41 | + return apply_frame(frame, model, now_us, source); |
| 42 | + } |
| 43 | + |
| 44 | + bool accept_octets(const uint8_t* bytes, |
| 45 | + size_t length, |
| 46 | + ship_data_model::DataModel<Real>& model, |
| 47 | + uint64_t now_us, |
| 48 | + ship_data_model::SensorSource source) { |
| 49 | + if (!bytes) return false; |
| 50 | + bool ok = true; |
| 51 | + for (size_t i = 0; i < length; ++i) { |
| 52 | + if (!accept_octet(bytes[i], model, now_us, source)) ok = false; |
| 53 | + } |
| 54 | + return ok; |
| 55 | + } |
| 56 | + |
| 57 | +private: |
| 58 | + bool apply_frame(const SeaTalkFrame& frame, |
| 59 | + ship_data_model::DataModel<Real>& model, |
| 60 | + uint64_t now_us, |
| 61 | + ship_data_model::SensorSource source) { |
| 62 | + SeaTalkDecoded<Real> decoded; |
| 63 | + if (!decode_seatalk_frame(frame, decoded)) { |
| 64 | + ++unsupported_count_; |
| 65 | + return true; |
| 66 | + } |
| 67 | + last_decoded_ = decoded; |
| 68 | + if (apply_seatalk_decoded(decoded, model, now_us, source)) { |
| 69 | + ++decoded_count_; |
| 70 | + return true; |
| 71 | + } |
| 72 | + ++unsupported_count_; |
| 73 | + return true; |
| 74 | + } |
| 75 | + |
| 76 | + SeaTalkRxState state_; |
| 77 | + SeaTalkDecoded<Real> last_decoded_; |
| 78 | + uint32_t decoded_count_ = 0; |
| 79 | + uint32_t unsupported_count_ = 0; |
| 80 | +}; |
| 81 | + |
| 82 | +} // namespace seatalk |
0 commit comments