mavtables  0.2.1
MAVLink router and firewall.
PacketQueue.hpp
Go to the documentation of this file.
1 // MAVLink router and firewall.
2 // Copyright (C) 2018 Michael R. Shannon <mrshannon.aerospace@gmail.com>
3 //
4 // This program is free software; you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation; either version 2 of the License, or
7 // (at your option) any later version.
8 //
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with this program. If not, see <http://www.gnu.org/licenses/>.
16 
17 
18 #ifndef PACKETQUEUE_HPP_
19 #define PACKETQUEUE_HPP_
20 
21 
22 #include <condition_variable>
23 #include <functional>
24 #include <memory>
25 #include <mutex>
26 #include <optional>
27 #include <queue>
28 
29 #include "config.hpp"
30 #include "Packet.hpp"
31 #include "QueuedPacket.hpp"
32 
33 
34 /** A threadsafe priority queue for MAVLink packets.
35  *
36  * This priority queue will order packets based on priority but also maintains
37  * insertion order among packets of the same priority.
38  *
39  * This is used to implement the packet priority of the firewall and to provide
40  * a queueing mechanism for packets when consumers are slower than the
41  * producers.
42  *
43  * \sa QueuedPacket
44  */
46 {
47  public:
48  PacketQueue(std::optional<std::function<void(void)>> callback = {});
49  // LCOV_EXCL_START
50  TEST_VIRTUAL ~PacketQueue() = default;
51  // LCOV_EXCL_STOP
52  TEST_VIRTUAL void close();
53  TEST_VIRTUAL bool empty();
54  TEST_VIRTUAL std::shared_ptr<const Packet> pop();
55  TEST_VIRTUAL std::shared_ptr<const Packet> pop(
56  const std::chrono::nanoseconds &timeout);
57  TEST_VIRTUAL void push(
58  std::shared_ptr<const Packet> packet, int priority = 0);
59 
60  private:
61  // Variables.
62  std::optional<std::function<void(void)>> callback_;
63  unsigned long long ticket_;
64  bool running_;
65  std::priority_queue<QueuedPacket> queue_;
66  std::mutex mutex_;
67  std::condition_variable cv_;
68  // Methods
69  std::shared_ptr<const Packet> get_packet_();
70 };
71 
72 
73 #endif // PACKETQUEUE_HPP_
TEST_VIRTUAL void close()
Definition: PacketQueue.cpp:70
TEST_VIRTUAL std::shared_ptr< const Packet > pop()
PacketQueue(std::optional< std::function< void(void)>> callback={})
Definition: PacketQueue.cpp:58
TEST_VIRTUAL ~PacketQueue()=default
TEST_VIRTUAL void push(std::shared_ptr< const Packet > packet, int priority=0)
TEST_VIRTUAL bool empty()
Definition: PacketQueue.cpp:87