Apollo 10.0
自动驾驶开放平台
message_reader.h
浏览该文件的文档.
1/******************************************************************************
2 * Copyright 2023 The Apollo Authors. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *****************************************************************************/
16
21#pragma once
22
23#include <functional>
24#include <map>
25#include <memory>
26#include <string>
27
28#include "cyber/common/macros.h"
29#include "cyber/cyber.h"
30
31namespace apollo { // namespace apollo
32namespace external_command { // namespace external_command
33
35 public:
40 template <typename T>
41 void RegisterMessage(const std::string& channel_name);
48 template <typename T>
49 const T* GetMessage(const std::string& channel_name) const;
50
51 private:
52 std::map<std::string, std::shared_ptr<cyber::ReaderBase>> reader_map_;
53 std::shared_ptr<cyber::Node> node_;
54
56};
57
58template <typename T>
59void MessageReader::RegisterMessage(const std::string& channel_name) {
60 // Only register reader when it is not registered before.
61 if (reader_map_.find(channel_name) == reader_map_.end()) {
62 auto reader = node_->CreateReader<T>(channel_name);
63 reader_map_[channel_name] = reader;
64 }
65}
66
67template <typename T>
68const T* MessageReader::GetMessage(const std::string& channel_name) const {
69 if (reader_map_.find(channel_name) == reader_map_.end()) {
70 return nullptr;
71 }
72 auto* base_reader = reader_map_.at(channel_name).get();
73 auto* message_reader = dynamic_cast<cyber::Reader<T>*>(base_reader);
74 if (nullptr == message_reader) {
75 return nullptr;
76 }
77 message_reader->Observe();
78 if (message_reader->Empty()) {
79 AERROR << "Failed to get message of " << channel_name;
80 return nullptr;
81 }
82 const auto* message = message_reader->GetLatestObserved().get();
83 return message;
84}
85
86} // namespace external_command
87} // namespace apollo
Reader subscribes a channel, it has two main functions:
Definition reader.h:69
void Observe() override
Get All data that Blocker stores
Definition reader.h:254
void RegisterMessage(const std::string &channel_name)
Register the message reader with the given channel name.
const T * GetMessage(const std::string &channel_name) const
Get the message with the channel name.
#define DECLARE_SINGLETON(classname)
Definition macros.h:52
#define AERROR
Definition log.h:44
class register implement
Definition arena_queue.h:37