repo_id
stringlengths
19
138
file_path
stringlengths
32
200
content
stringlengths
1
12.9M
__index_level_0__
int64
0
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/logger/log_file_object_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/logger/log_file_object.h" #include <string> #include "gtest/gtest.h" #include "glog/logging.h" #include "cyber/cyber.h" #include "cyber/time/time.h" namespace apollo { namespace cyber { namespace logger { TEST(LogFileObjectTest, init_and_write) { std::string basename = "logfile"; LogFileObject logfileobject(google::INFO, basename.c_str()); logfileobject.SetBasename("base"); time_t timep; time(&timep); std::string message = "cyber logger test"; logfileobject.Write(false, timep, message.c_str(), 20); logfileobject.SetExtension("unittest"); logfileobject.Flush(); } } // namespace logger } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/logger/logger_util_test.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/logger/logger_util.h" #include <algorithm> #include <sstream> #include <string> #include <utility> #include "gtest/gtest.h" #include "cyber/common/log.h" namespace apollo { namespace cyber { namespace logger { TEST(LoggerUtilTest, GetHostName) { std::string host_name; GetHostName(&host_name); EXPECT_FALSE(host_name.empty()); } TEST(LoggerUtilTest, FindModuleName) { std::string module_name = "module_name_0"; std::string log_message = LEFT_BRACKET; FindModuleName(&log_message, &module_name); EXPECT_EQ("module_name_0", module_name); log_message = RIGHT_BRACKET; FindModuleName(&log_message, &module_name); EXPECT_EQ("module_name_0", module_name); log_message = LEFT_BRACKET; log_message.append("module_name_1"); log_message.append(RIGHT_BRACKET); FindModuleName(&log_message, &module_name); EXPECT_EQ("module_name_1", module_name); log_message = "123"; log_message.append(LEFT_BRACKET); log_message.append("module_name_2"); log_message.append(RIGHT_BRACKET); log_message.append("123"); FindModuleName(&log_message, &module_name); EXPECT_EQ("module_name_2", module_name); log_message = "123"; log_message.append(LEFT_BRACKET); log_message.append(RIGHT_BRACKET); log_message.append("123"); FindModuleName(&log_message, &module_name); EXPECT_EQ("logger_util_test_" + std::to_string(GetMainThreadPid()), module_name); } TEST(LoggerUtilTest, MaxLogSize) { FLAGS_max_log_size = 10; EXPECT_EQ(10, MaxLogSize()); FLAGS_max_log_size = 0; EXPECT_EQ(1, MaxLogSize()); } TEST(LoggerUtilTest, PidHasChanged) { EXPECT_FALSE(PidHasChanged()); } } // namespace logger } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/logger/logger.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef CYBER_LOGGER_LOGGER_H_ #define CYBER_LOGGER_LOGGER_H_ #include <mutex> #include "glog/logging.h" namespace apollo { namespace cyber { namespace logger { class Logger : public google::base::Logger { public: explicit Logger(google::base::Logger* wrapped); ~Logger(); void Write(bool force_flush, time_t timestamp, const char* message, int message_len) override; void Flush() override; uint32_t LogSize() override; private: google::base::Logger* const wrapped_; std::mutex mutex_; }; } // namespace logger } // namespace cyber } // namespace apollo #endif // CYBER_LOGGER_LOGGER_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/logger/log_file_object.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef CYBER_LOGGER_LOG_FILE_OBJECT_H_ #define CYBER_LOGGER_LOG_FILE_OBJECT_H_ #include <cstdint> #include <iomanip> #include <mutex> #include <string> #include "glog/logging.h" namespace apollo { namespace cyber { namespace logger { // the C99 format typedef int32_t int32; typedef uint32_t uint32; typedef int64_t int64; typedef uint64_t uint64; using google::LogSeverity; using google::NUM_SEVERITIES; using std::ostringstream; using std::setw; using std::string; // Encapsulates all file-system related state class LogFileObject : public google::base::Logger { public: LogFileObject(LogSeverity severity, const char* base_filename); ~LogFileObject(); void Write(bool force_flush, // Should we force a flush here? time_t timestamp, // Timestamp for this entry const char* message, int message_len) override; // Configuration options void SetBasename(const char* basename); void SetExtension(const char* ext); void SetSymlinkBasename(const char* symlink_basename); // Normal flushing routine void Flush() override; // It is the actual file length for the system loggers, // i.e., INFO, ERROR, etc. uint32 LogSize() override { std::lock_guard<std::mutex> lock(lock_); return file_length_; } // Internal flush routine. Exposed so that FlushLogFilesUnsafe() // can avoid grabbing a lock. Usually Flush() calls it after // acquiring lock_. void FlushUnlocked(); const string& hostname(); private: static const uint32 kRolloverAttemptFrequency = 0x20; std::mutex lock_; bool base_filename_selected_; string base_filename_; string symlink_basename_; string filename_extension_; // option users can specify (eg to add port#) FILE* file_; LogSeverity severity_; uint32 bytes_since_flush_; uint32 file_length_; unsigned int rollover_attempt_; int64 next_flush_time_; // cycle count at which to flush log string hostname_; // Actually create a logfile using the value of base_filename_ and the // supplied argument time_pid_string // REQUIRES: lock_ is held bool CreateLogfile(const string& time_pid_string); }; } // namespace logger } // namespace cyber } // namespace apollo #endif // CYBER_LOGGER_LOG_FILE_OBJECT_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/record/record_viewer_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/record/record_viewer.h" #include <unistd.h> #include <algorithm> #include <atomic> #include <memory> #include <string> #include "gtest/gtest.h" #include "cyber/common/log.h" #include "cyber/record/record_reader.h" #include "cyber/record/record_writer.h" namespace apollo { namespace cyber { namespace record { using apollo::cyber::message::RawMessage; constexpr char kChannelName1[] = "/test/channel1"; constexpr char kMessageType1[] = "apollo.cyber.proto.Test"; constexpr char kProtoDesc1[] = "1234567890"; constexpr char kTestFile[] = "viewer_test.record"; static void ConstructRecord(uint64_t msg_num, uint64_t begin_time, uint64_t time_step, bool reverse = false) { RecordWriter writer; writer.SetSizeOfFileSegmentation(0); writer.SetIntervalOfFileSegmentation(0); writer.Open(kTestFile); writer.WriteChannel(kChannelName1, kMessageType1, kProtoDesc1); for (uint64_t i = 0; i < msg_num; i++) { auto ai = i; if (reverse) { ai = msg_num - 1 - i; } auto msg = std::make_shared<RawMessage>(std::to_string(ai)); writer.WriteMessage(kChannelName1, msg, begin_time + time_step * ai); } ASSERT_EQ(msg_num, writer.GetMessageNumber(kChannelName1)); writer.Close(); } uint64_t CheckCount(RecordViewer viewer) { int i = 0; for (auto& msg : viewer) { if (msg.time >= 0) { i++; } } return i; } TEST(RecordTest, iterator_test) { uint64_t msg_num = 200; uint64_t begin_time = 100000000; uint64_t step_time = 100000000; // 100ms uint64_t end_time = begin_time + step_time * (msg_num - 1); ConstructRecord(msg_num, begin_time, step_time); auto reader = std::make_shared<RecordReader>(kTestFile); RecordViewer viewer(reader); EXPECT_TRUE(viewer.IsValid()); EXPECT_EQ(begin_time, viewer.begin_time()); EXPECT_EQ(end_time, viewer.end_time()); uint64_t i = 0; for (auto& msg : viewer) { EXPECT_EQ(kChannelName1, msg.channel_name); EXPECT_EQ(begin_time + step_time * i, msg.time); EXPECT_EQ(std::to_string(i), msg.content); i++; } EXPECT_EQ(msg_num, i); i = 0; std::for_each(viewer.begin(), viewer.end(), [&i](RecordMessage& msg) { EXPECT_EQ(kChannelName1, msg.channel_name); // EXPECT_EQ(begin_time + step_time * i, msg.time); EXPECT_EQ(std::to_string(i), msg.content); i++; }); EXPECT_EQ(msg_num, i); i = 0; for (auto it = viewer.begin(); it != viewer.end(); ++it) { EXPECT_EQ(kChannelName1, it->channel_name); EXPECT_EQ(begin_time + step_time * i, it->time); EXPECT_EQ(std::to_string(i), it->content); i++; } EXPECT_EQ(msg_num, i); ASSERT_FALSE(remove(kTestFile)); } TEST(RecordTest, iterator_test_reverse) { uint64_t msg_num = 200; uint64_t begin_time = 1000; uint64_t step_time = 10; // TODO(storypku): investigtate why the following fails // uint64_t begin_time = 100000000; // uint64_t step_time = 100000000; // 100ms uint64_t end_time = begin_time + step_time * (msg_num - 1); ConstructRecord(msg_num, begin_time, step_time, true); auto reader = std::make_shared<RecordReader>(kTestFile); RecordViewer viewer(reader); EXPECT_TRUE(viewer.IsValid()); EXPECT_EQ(begin_time, viewer.begin_time()); EXPECT_EQ(end_time, viewer.end_time()); uint64_t i = 0; for (auto& msg : viewer) { EXPECT_EQ(kChannelName1, msg.channel_name); EXPECT_EQ(begin_time + step_time * i, msg.time); EXPECT_EQ(std::to_string(i), msg.content); i++; } EXPECT_EQ(msg_num, i); i = 0; for (auto it = viewer.begin(); it != viewer.end(); ++it) { EXPECT_EQ(kChannelName1, it->channel_name); EXPECT_EQ(begin_time + step_time * i, it->time); EXPECT_EQ(std::to_string(i), it->content); i++; } EXPECT_EQ(msg_num, i); ASSERT_FALSE(remove(kTestFile)); } TEST(RecordTest, filter_test) { uint64_t msg_num = 200; uint64_t begin_time = 100000000; uint64_t step_time = 100000000; // 100ms uint64_t end_time = begin_time + step_time * (msg_num - 1); ConstructRecord(msg_num, begin_time, step_time); auto reader = std::make_shared<RecordReader>(kTestFile); RecordViewer viewer_0(reader); EXPECT_EQ(CheckCount(viewer_0), msg_num); EXPECT_EQ(begin_time, viewer_0.begin_time()); EXPECT_EQ(end_time, viewer_0.end_time()); RecordViewer viewer_1(reader, end_time, end_time); EXPECT_EQ(CheckCount(viewer_1), 1); EXPECT_EQ(end_time, viewer_1.begin_time()); RecordViewer viewer_2(reader, end_time, begin_time); EXPECT_EQ(CheckCount(viewer_2), 0); EXPECT_EQ(begin_time, viewer_2.end_time()); viewer_0.begin(); viewer_0.begin(); // filter first message RecordViewer viewer_3(reader, begin_time + 1, end_time); EXPECT_EQ(CheckCount(viewer_3), msg_num - 1); // filter last message RecordViewer viewer_4(reader, begin_time, end_time - 1); EXPECT_EQ(CheckCount(viewer_4), msg_num - 1); auto it_1 = viewer_3.begin(); auto it_2 = viewer_4.begin(); EXPECT_NE(it_1, it_2); // pick 2 frame RecordViewer viewer_5(reader, begin_time + 12 * step_time, begin_time + 13 * step_time); EXPECT_EQ(CheckCount(viewer_5), 2); // filter with not exist channel RecordViewer viewer_6(reader, 0, end_time, {"null"}); EXPECT_EQ(CheckCount(viewer_6), 0); // filter with exist channel RecordViewer viewer_7(reader, 0, end_time, {kChannelName1}); EXPECT_EQ(CheckCount(viewer_7), msg_num); ASSERT_FALSE(remove(kTestFile)); } TEST(RecordTest, mult_iterator_test) { uint64_t msg_num = 200; uint64_t begin_time = 100000000; uint64_t step_time = 100000000; // 100ms uint64_t end_time = begin_time + step_time * (msg_num - 1); ConstructRecord(msg_num, begin_time, step_time); auto reader = std::make_shared<RecordReader>(kTestFile); RecordViewer viewer(reader); EXPECT_TRUE(viewer.IsValid()); EXPECT_EQ(begin_time, viewer.begin_time()); EXPECT_EQ(end_time, viewer.end_time()); auto bg = viewer.begin(); // #1 iterator uint64_t i = 0; for (auto& msg : viewer) { // #2 iterator EXPECT_EQ(kChannelName1, msg.channel_name); EXPECT_EQ(begin_time + step_time * i, msg.time); EXPECT_EQ(std::to_string(i), msg.content); i++; } EXPECT_EQ(msg_num, i); ASSERT_FALSE(remove(kTestFile)); } } // namespace record } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/record/record_viewer.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/record/record_viewer.h" #include <algorithm> #include <limits> #include <utility> #include "cyber/common/log.h" namespace apollo { namespace cyber { namespace record { RecordViewer::RecordViewer(const RecordReaderPtr& reader, uint64_t begin_time, uint64_t end_time, const std::set<std::string>& channels) : begin_time_(begin_time), end_time_(end_time), channels_(channels), readers_({reader}) { Init(); UpdateTime(); } RecordViewer::RecordViewer(const std::vector<RecordReaderPtr>& readers, uint64_t begin_time, uint64_t end_time, const std::set<std::string>& channels) : begin_time_(begin_time), end_time_(end_time), channels_(channels), readers_(readers) { Init(); UpdateTime(); } bool RecordViewer::IsValid() const { if (begin_time_ > end_time_) { AERROR << "Begin time must be earlier than end time" << ", begin_time=" << begin_time_ << ", end_time=" << end_time_; return false; } return true; } bool RecordViewer::Update(RecordMessage* message) { bool find = false; do { if (msg_buffer_.empty() && !FillBuffer()) { break; } auto& msg = msg_buffer_.begin()->second; if (channels_.empty() || channels_.count(msg->channel_name) == 1) { *message = *msg; find = true; } msg_buffer_.erase(msg_buffer_.begin()); } while (!find); return find; } RecordViewer::Iterator RecordViewer::begin() { return Iterator(this); } RecordViewer::Iterator RecordViewer::end() { return Iterator(this, true); } void RecordViewer::Init() { // Init the channel list for (auto& reader : readers_) { auto all_channel = reader->GetChannelList(); std::set_intersection(all_channel.begin(), all_channel.end(), channels_.begin(), channels_.end(), std::inserter(channel_list_, channel_list_.end())); } readers_finished_.resize(readers_.size(), false); // Sort the readers std::sort(readers_.begin(), readers_.end(), [](const RecordReaderPtr& lhs, const RecordReaderPtr& rhs) { const auto& lhs_header = lhs->GetHeader(); const auto& rhs_header = rhs->GetHeader(); if (lhs_header.begin_time() == rhs_header.begin_time()) { return lhs_header.end_time() < rhs_header.end_time(); } return lhs_header.begin_time() < rhs_header.begin_time(); }); } void RecordViewer::Reset() { for (auto& reader : readers_) { reader->Reset(); } std::fill(readers_finished_.begin(), readers_finished_.end(), false); curr_begin_time_ = begin_time_; msg_buffer_.clear(); } void RecordViewer::UpdateTime() { uint64_t min_begin_time = std::numeric_limits<uint64_t>::max(); uint64_t max_end_time = 0; for (auto& reader : readers_) { if (!reader->IsValid()) { continue; } const auto& header = reader->GetHeader(); if (min_begin_time > header.begin_time()) { min_begin_time = header.begin_time(); } if (max_end_time < header.end_time()) { max_end_time = header.end_time(); } } if (begin_time_ < min_begin_time) { begin_time_ = min_begin_time; } if (end_time_ > max_end_time) { end_time_ = max_end_time; } curr_begin_time_ = begin_time_; } bool RecordViewer::FillBuffer() { while (curr_begin_time_ <= end_time_ && msg_buffer_.size() < kBufferMinSize) { uint64_t this_begin_time = curr_begin_time_; uint64_t this_end_time = this_begin_time + kStepTimeNanoSec; if (this_end_time > end_time_) { this_end_time = end_time_; } for (size_t i = 0; i < readers_.size(); ++i) { if (!readers_finished_[i] && readers_[i]->GetHeader().end_time() < this_begin_time) { readers_finished_[i] = true; readers_[i]->Reset(); } } for (size_t i = 0; i < readers_.size(); ++i) { if (readers_finished_[i]) { continue; } auto& reader = readers_[i]; while (true) { auto record_msg = std::make_shared<RecordMessage>(); if (!reader->ReadMessage(record_msg.get(), this_begin_time, this_end_time)) { break; } msg_buffer_.emplace(std::make_pair(record_msg->time, record_msg)); } } // because ReadMessage of RecordReader is closed interval, so we add 1 here curr_begin_time_ = this_end_time + 1; } return !msg_buffer_.empty(); } RecordViewer::Iterator::Iterator(RecordViewer* viewer, bool end) : end_(end), viewer_(viewer) { if (end_) { return; } viewer_->Reset(); if (!viewer_->IsValid() || !viewer_->Update(&message_instance_)) { end_ = true; } } bool RecordViewer::Iterator::operator==(Iterator const& other) const { if (other.end_) { return end_; } return index_ == other.index_ && viewer_ == other.viewer_; } bool RecordViewer::Iterator::operator!=(const Iterator& rhs) const { return !(*this == rhs); } RecordViewer::Iterator& RecordViewer::Iterator::operator++() { index_++; if (!viewer_->Update(&message_instance_)) { end_ = true; } return *this; } RecordViewer::Iterator::pointer RecordViewer::Iterator::operator->() { return &message_instance_; } RecordViewer::Iterator::reference RecordViewer::Iterator::operator*() { return message_instance_; } } // namespace record } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/record/record_viewer.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef CYBER_RECORD_RECORD_VIEWER_H_ #define CYBER_RECORD_RECORD_VIEWER_H_ #include <cstddef> #include <limits> #include <map> #include <memory> #include <set> #include <string> #include <vector> #include "cyber/record/record_message.h" #include "cyber/record/record_reader.h" namespace apollo { namespace cyber { namespace record { /** * @brief The record viewer. */ class RecordViewer { public: using RecordReaderPtr = std::shared_ptr<RecordReader>; /** * @brief The constructor with single reader. * * @param reader * @param begin_time * @param end_time * @param channels */ RecordViewer(const RecordReaderPtr& reader, uint64_t begin_time = 0, uint64_t end_time = std::numeric_limits<uint64_t>::max(), const std::set<std::string>& channels = {}); /** * @brief The constructor with multiple readers. * * @param readers * @param begin_time * @param end_time * @param channels */ RecordViewer(const std::vector<RecordReaderPtr>& readers, uint64_t begin_time = 0, uint64_t end_time = std::numeric_limits<uint64_t>::max(), const std::set<std::string>& channels = std::set<std::string>()); /** * @brief Is this record reader is valid. * * @return True for valid, false for not. */ bool IsValid() const; /** * @brief Get begin time. * * @return Begin time (nanoseconds). */ uint64_t begin_time() const { return begin_time_; } /** * @brief Get end time. * * @return end time (nanoseconds). */ uint64_t end_time() const { return end_time_; } /** * @brief Get channel list. * * @return List container with all channel name string. */ std::set<std::string> GetChannelList() const { return channel_list_; } /** * @brief The iterator. */ class Iterator : public std::iterator<std::input_iterator_tag, RecordMessage, int, RecordMessage*, RecordMessage&> { public: /** * @brief The constructor of iterator with viewer. * * @param viewer * @param end */ explicit Iterator(RecordViewer* viewer, bool end = false); /** * @brief The default constructor of iterator. */ Iterator() {} /** * @brief The default destructor of iterator. */ virtual ~Iterator() {} /** * @brief Overloading operator ==. * * @param other * * @return The result. */ bool operator==(Iterator const& other) const; /** * @brief Overloading operator !=. * * @param other * * @return The result. */ bool operator!=(const Iterator& rhs) const; /** * @brief Overloading operator ++. * * @return The result. */ Iterator& operator++(); /** * @brief Overloading operator ->. * * @return The pointer. */ pointer operator->(); /** * @brief Overloading operator *. * * @return The reference. */ reference operator*(); private: bool end_ = false; uint64_t index_ = 0; RecordViewer* viewer_ = nullptr; value_type message_instance_; }; /** * @brief Get the begin iterator. * * @return The begin iterator. */ Iterator begin(); /** * @brief Get the end iterator. * * @return The end iterator. */ Iterator end(); private: friend class Iterator; void Init(); void Reset(); void UpdateTime(); bool FillBuffer(); bool Update(RecordMessage* message); uint64_t begin_time_ = 0; uint64_t end_time_ = std::numeric_limits<uint64_t>::max(); // User defined channels std::set<std::string> channels_; // All channel in user defined readers std::set<std::string> channel_list_; std::vector<RecordReaderPtr> readers_; std::vector<bool> readers_finished_; uint64_t curr_begin_time_ = 0; std::multimap<uint64_t, std::shared_ptr<RecordMessage>> msg_buffer_; const uint64_t kStepTimeNanoSec = 1000000000UL; // 1 second const std::size_t kBufferMinSize = 128; }; } // namespace record } // namespace cyber } // namespace apollo #endif // CYBER_RECORD_RECORD_VIEWER_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/record/record_reader_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/record/record_reader.h" #include <string> #include "gtest/gtest.h" #include "cyber/record/record_writer.h" namespace apollo { namespace cyber { namespace record { using apollo::cyber::message::RawMessage; constexpr char kChannelName1[] = "/test/channel1"; constexpr char kMessageType1[] = "apollo.cyber.proto.Test"; constexpr char kProtoDesc[] = "1234567890"; constexpr char kStr10B[] = "1234567890"; constexpr char kTestFile[] = "record_reader_test.record"; constexpr uint32_t kMessageNum = 16; TEST(RecordTest, TestSingleRecordFile) { RecordWriter writer; writer.SetSizeOfFileSegmentation(0); writer.SetIntervalOfFileSegmentation(0); writer.Open(kTestFile); writer.WriteChannel(kChannelName1, kMessageType1, kProtoDesc); for (uint32_t i = 0; i < kMessageNum; ++i) { auto msg = std::make_shared<RawMessage>(std::to_string(i)); writer.WriteMessage(kChannelName1, msg, i); } ASSERT_EQ(kMessageNum, writer.GetMessageNumber(kChannelName1)); ASSERT_EQ(kMessageType1, writer.GetMessageType(kChannelName1)); ASSERT_EQ(kProtoDesc, writer.GetProtoDesc(kChannelName1)); writer.Close(); RecordReader reader(kTestFile); RecordMessage message; ASSERT_EQ(kMessageNum, reader.GetMessageNumber(kChannelName1)); ASSERT_EQ(kMessageType1, reader.GetMessageType(kChannelName1)); ASSERT_EQ(kProtoDesc, reader.GetProtoDesc(kChannelName1)); // read all message uint32_t i = 0; for (i = 0; i < kMessageNum; ++i) { ASSERT_TRUE(reader.ReadMessage(&message)); ASSERT_EQ(kChannelName1, message.channel_name); ASSERT_EQ(std::to_string(i), message.content); ASSERT_EQ(i, message.time); } ASSERT_FALSE(reader.ReadMessage(&message)); // skip first message reader.Reset(); for (i = 0; i < kMessageNum - 1; ++i) { ASSERT_TRUE(reader.ReadMessage(&message, 1)); ASSERT_EQ(kChannelName1, message.channel_name); ASSERT_EQ(std::to_string(i + 1), message.content); ASSERT_EQ(i + 1, message.time); } ASSERT_FALSE(reader.ReadMessage(&message, 1)); // skip last message reader.Reset(); for (i = 0; i < kMessageNum - 1; ++i) { ASSERT_TRUE(reader.ReadMessage(&message, 0, kMessageNum - 2)); ASSERT_EQ(kChannelName1, message.channel_name); ASSERT_EQ(std::to_string(i), message.content); ASSERT_EQ(i, message.time); } ASSERT_FALSE(reader.ReadMessage(&message, 0, kMessageNum - 2)); ASSERT_FALSE(remove(kTestFile)); } TEST(RecordTest, TestReaderOrder) { RecordWriter writer; writer.SetSizeOfFileSegmentation(0); writer.SetIntervalOfFileSegmentation(0); writer.Open(kTestFile); writer.WriteChannel(kChannelName1, kMessageType1, kProtoDesc); for (uint32_t i = kMessageNum; i > 0; --i) { auto msg = std::make_shared<RawMessage>(std::to_string(i)); writer.WriteMessage(kChannelName1, msg, i * 100); } ASSERT_EQ(kMessageNum, writer.GetMessageNumber(kChannelName1)); ASSERT_EQ(kMessageType1, writer.GetMessageType(kChannelName1)); ASSERT_EQ(kProtoDesc, writer.GetProtoDesc(kChannelName1)); writer.Close(); RecordReader reader(kTestFile); RecordMessage message; ASSERT_EQ(kMessageNum, reader.GetMessageNumber(kChannelName1)); ASSERT_EQ(kMessageType1, reader.GetMessageType(kChannelName1)); ASSERT_EQ(kProtoDesc, reader.GetProtoDesc(kChannelName1)); // read all message for (uint32_t i = 1; i <= kMessageNum; ++i) { ASSERT_TRUE(reader.ReadMessage(&message)); ASSERT_EQ(kChannelName1, message.channel_name); ASSERT_NE(std::to_string(i), message.content); ASSERT_NE(i * 100, message.time); } ASSERT_FALSE(reader.ReadMessage(&message)); ASSERT_FALSE(remove(kTestFile)); } } // namespace record } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/record/record_reader.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef CYBER_RECORD_RECORD_READER_H_ #define CYBER_RECORD_RECORD_READER_H_ #include <limits> #include <memory> #include <set> #include <string> #include <unordered_map> #include "cyber/proto/record.pb.h" #include "cyber/record/file/record_file_reader.h" #include "cyber/record/record_base.h" #include "cyber/record/record_message.h" namespace apollo { namespace cyber { namespace record { /** * @brief The record reader. */ class RecordReader : public RecordBase { public: using FileReaderPtr = std::unique_ptr<RecordFileReader>; using ChannelInfoMap = std::unordered_map<std::string, proto::ChannelCache>; /** * @brief The constructor with record file path as parameter. * * @param file */ explicit RecordReader(const std::string& file); /** * @brief The destructor. */ virtual ~RecordReader(); /** * @brief Is this record reader is valid. * * @return True for valid, false for not. */ bool IsValid() const { return is_valid_; } /** * @brief Read one message from reader. * * @param message * @param begin_time * @param end_time * * @return True for success, false for not. */ bool ReadMessage(RecordMessage* message, uint64_t begin_time = 0, uint64_t end_time = std::numeric_limits<uint64_t>::max()); /** * @brief Reset the message index of record reader. */ void Reset(); /** * @brief Get message number by channel name. * * @param channel_name * * @return Message number. */ uint64_t GetMessageNumber(const std::string& channel_name) const override; /** * @brief Get message type by channel name. * * @param channel_name * * @return Message type. */ const std::string& GetMessageType( const std::string& channel_name) const override; /** * @brief Get proto descriptor string by channel name. * * @param channel_name * * @return Proto descriptor string by channel name. */ const std::string& GetProtoDesc( const std::string& channel_name) const override; /** * @brief Get channel list. * * @return List container with all channel name string. */ std::set<std::string> GetChannelList() const override; private: bool ReadNextChunk(uint64_t begin_time, uint64_t end_time); bool is_valid_ = false; bool reach_end_ = false; std::unique_ptr<proto::ChunkBody> chunk_ = nullptr; proto::Index index_; int message_index_ = 0; ChannelInfoMap channel_info_; FileReaderPtr file_reader_; }; } // namespace record } // namespace cyber } // namespace apollo #endif // CYBER_RECORD_RECORD_READER_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/record/record_reader.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/record/record_reader.h" #include <utility> namespace apollo { namespace cyber { namespace record { using apollo::cyber::proto::Channel; using apollo::cyber::proto::ChunkBody; using apollo::cyber::proto::ChunkHeader; using apollo::cyber::proto::SectionType; RecordReader::~RecordReader() {} RecordReader::RecordReader(const std::string& file) { file_reader_.reset(new RecordFileReader()); if (!file_reader_->Open(file)) { AERROR << "Failed to open record file: " << file; return; } chunk_.reset(new ChunkBody()); is_valid_ = true; header_ = file_reader_->GetHeader(); if (file_reader_->ReadIndex()) { index_ = file_reader_->GetIndex(); for (int i = 0; i < index_.indexes_size(); ++i) { auto single_idx = index_.mutable_indexes(i); if (single_idx->type() != SectionType::SECTION_CHANNEL) { continue; } if (!single_idx->has_channel_cache()) { AERROR << "Single channel index does not have channel_cache."; continue; } auto channel_cache = single_idx->mutable_channel_cache(); channel_info_.insert( std::make_pair(channel_cache->name(), *channel_cache)); } } file_reader_->Reset(); } void RecordReader::Reset() { file_reader_->Reset(); reach_end_ = false; message_index_ = 0; chunk_.reset(new ChunkBody()); } std::set<std::string> RecordReader::GetChannelList() const { std::set<std::string> channel_list; for (auto& item : channel_info_) { channel_list.insert(item.first); } return channel_list; } bool RecordReader::ReadMessage(RecordMessage* message, uint64_t begin_time, uint64_t end_time) { if (!is_valid_) { return false; } if (begin_time > header_.end_time() || end_time < header_.begin_time()) { return false; } while (message_index_ < chunk_->messages_size()) { const auto& next_message = chunk_->messages(message_index_); uint64_t time = next_message.time(); if (time > end_time) { return false; } ++message_index_; if (time < begin_time) { continue; } message->channel_name = next_message.channel_name(); message->content = next_message.content(); message->time = time; return true; } ADEBUG << "Read next chunk."; if (ReadNextChunk(begin_time, end_time)) { ADEBUG << "Read chunk successfully."; message_index_ = 0; return ReadMessage(message, begin_time, end_time); } ADEBUG << "No chunk to read."; return false; } bool RecordReader::ReadNextChunk(uint64_t begin_time, uint64_t end_time) { bool skip_next_chunk_body = false; while (!reach_end_) { Section section; if (!file_reader_->ReadSection(&section)) { AERROR << "Failed to read section, file: " << file_reader_->GetPath(); return false; } switch (section.type) { case SectionType::SECTION_INDEX: { file_reader_->SkipSection(section.size); reach_end_ = true; break; } case SectionType::SECTION_CHANNEL: { ADEBUG << "Read channel section of size: " << section.size; Channel channel; if (!file_reader_->ReadSection<Channel>(section.size, &channel)) { AERROR << "Failed to read channel section."; return false; } break; } case SectionType::SECTION_CHUNK_HEADER: { ADEBUG << "Read chunk header section of size: " << section.size; ChunkHeader header; if (!file_reader_->ReadSection<ChunkHeader>(section.size, &header)) { AERROR << "Failed to read chunk header section."; return false; } if (header.end_time() < begin_time) { skip_next_chunk_body = true; } if (header.begin_time() > end_time) { return false; } break; } case SectionType::SECTION_CHUNK_BODY: { if (skip_next_chunk_body) { file_reader_->SkipSection(section.size); skip_next_chunk_body = false; break; } chunk_.reset(new ChunkBody()); if (!file_reader_->ReadSection<ChunkBody>(section.size, chunk_.get())) { AERROR << "Failed to read chunk body section."; return false; } return true; } default: { AERROR << "Invalid section, type: " << section.type << ", size: " << section.size; return false; } } } return false; } uint64_t RecordReader::GetMessageNumber(const std::string& channel_name) const { auto search = channel_info_.find(channel_name); if (search == channel_info_.end()) { return 0; } return search->second.message_number(); } const std::string& RecordReader::GetMessageType( const std::string& channel_name) const { auto search = channel_info_.find(channel_name); if (search == channel_info_.end()) { return kEmptyString; } return search->second.message_type(); } const std::string& RecordReader::GetProtoDesc( const std::string& channel_name) const { auto search = channel_info_.find(channel_name); if (search == channel_info_.end()) { return kEmptyString; } return search->second.proto_desc(); } } // namespace record } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/record/record_message.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef CYBER_RECORD_RECORD_MESSAGE_H_ #define CYBER_RECORD_RECORD_MESSAGE_H_ #include <cstdint> #include <string> namespace apollo { namespace cyber { namespace record { static constexpr size_t kGB = 1 << 30; static constexpr size_t kMB = 1 << 20; static constexpr size_t kKB = 1 << 10; /** * @brief Basic data struct of record message. */ struct RecordMessage { /** * @brief The constructor. */ RecordMessage() {} /** * @brief The constructor. * * @param name * @param message * @param msg_time */ RecordMessage(const std::string& name, const std::string& message, uint64_t msg_time) : channel_name(name), content(message), time(msg_time) {} /** * @brief The channel name of the message. */ std::string channel_name; /** * @brief The content of the message. */ std::string content; /** * @brief The time (nanosecond) of the message. */ uint64_t time; }; } // namespace record } // namespace cyber } // namespace apollo #endif // CYBER_RECORD_RECORD_READER_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/record/record_writer.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/record/record_writer.h" #include <iomanip> #include <iostream> #include "cyber/common/log.h" namespace apollo { namespace cyber { namespace record { using proto::Channel; using proto::SingleMessage; RecordWriter::RecordWriter() { header_ = HeaderBuilder::GetHeader(); } RecordWriter::RecordWriter(const proto::Header& header) { header_ = header; } RecordWriter::~RecordWriter() { Close(); } bool RecordWriter::Open(const std::string& file) { file_ = file; file_index_ = 0; sstream_.str(std::string()); sstream_.clear(); sstream_ << "." << std::setw(5) << std::setfill('0') << file_index_++; if (header_.segment_interval() > 0 || header_.segment_raw_size() > 0) { path_ = file_ + sstream_.str(); } else { path_ = file_; } file_writer_.reset(new RecordFileWriter()); if (!file_writer_->Open(path_)) { AERROR << "Failed to open output record file: " << path_; return false; } if (!file_writer_->WriteHeader(header_)) { AERROR << "Failed to write header: " << path_; file_writer_->Close(); return false; } is_opened_ = true; return is_opened_; } void RecordWriter::Close() { if (is_opened_) { file_writer_->Close(); is_opened_ = false; } } bool RecordWriter::SplitOutfile() { file_writer_.reset(new RecordFileWriter()); if (file_index_ > 99999) { AWARN << "More than 99999 record files had been recored, will restart " << "counting from 0."; file_index_ = 0; } sstream_.str(std::string()); sstream_.clear(); sstream_ << "." << std::setw(5) << std::setfill('0') << file_index_++; path_ = file_ + sstream_.str(); segment_raw_size_ = 0; segment_begin_time_ = 0; if (!file_writer_->Open(path_)) { AERROR << "Failed to open record file: " << path_; return false; } if (!file_writer_->WriteHeader(header_)) { AERROR << "Failed to write header for record file: " << path_; return false; } for (const auto& i : channel_message_number_map_) { Channel channel; channel.set_name(i.first); channel.set_message_type(channel_message_type_map_[i.first]); channel.set_proto_desc(channel_proto_desc_map_[i.first]); if (!file_writer_->WriteChannel(channel)) { AERROR << "Failed to write channel for record file: " << path_; return false; } } return true; } bool RecordWriter::WriteChannel(const std::string& channel_name, const std::string& message_type, const std::string& proto_desc) { std::lock_guard<std::mutex> lg(mutex_); if (IsNewChannel(channel_name)) { OnNewChannel(channel_name, message_type, proto_desc); Channel channel; channel.set_name(channel_name); channel.set_message_type(message_type); channel.set_proto_desc(proto_desc); if (!file_writer_->WriteChannel(channel)) { AERROR << "Failed to write channel: " << channel_name; return false; } } else { AWARN << "Intercept write channel request, duplicate channel: " << channel_name; } return true; } bool RecordWriter::WriteMessage(const SingleMessage& message) { std::lock_guard<std::mutex> lg(mutex_); OnNewMessage(message.channel_name()); if (!file_writer_->WriteMessage(message)) { AERROR << "Write message is failed."; return false; } segment_raw_size_ += message.content().size(); if (segment_begin_time_ == 0) { segment_begin_time_ = message.time(); } if (segment_begin_time_ > message.time()) { segment_begin_time_ = message.time(); } if ((header_.segment_interval() > 0 && message.time() - segment_begin_time_ > header_.segment_interval()) || (header_.segment_raw_size() > 0 && segment_raw_size_ > header_.segment_raw_size())) { file_writer_backup_.swap(file_writer_); file_writer_backup_->Close(); if (!SplitOutfile()) { AERROR << "Split out file is failed."; return false; } } return true; } bool RecordWriter::SetSizeOfFileSegmentation(uint64_t size_kilobytes) { if (is_opened_) { AWARN << "Please call this interface before opening file."; return false; } header_.set_segment_raw_size(size_kilobytes * 1024UL); return true; } bool RecordWriter::SetIntervalOfFileSegmentation(uint64_t time_sec) { if (is_opened_) { AWARN << "Please call this interface before opening file."; return false; } header_.set_segment_interval(time_sec * 1000000000UL); return true; } bool RecordWriter::IsNewChannel(const std::string& channel_name) const { return channel_message_number_map_.find(channel_name) == channel_message_number_map_.end(); } void RecordWriter::OnNewChannel(const std::string& channel_name, const std::string& message_type, const std::string& proto_desc) { channel_message_number_map_[channel_name] = 0; channel_message_type_map_[channel_name] = message_type; channel_proto_desc_map_[channel_name] = proto_desc; } void RecordWriter::OnNewMessage(const std::string& channel_name) { auto iter = channel_message_number_map_.find(channel_name); if (iter != channel_message_number_map_.end()) { iter->second++; } } uint64_t RecordWriter::GetMessageNumber(const std::string& channel_name) const { auto search = channel_message_number_map_.find(channel_name); if (search != channel_message_number_map_.end()) { return search->second; } return 0; } const std::string& RecordWriter::GetMessageType( const std::string& channel_name) const { auto search = channel_message_type_map_.find(channel_name); if (search != channel_message_type_map_.end()) { return search->second; } return kEmptyString; } const std::string& RecordWriter::GetProtoDesc( const std::string& channel_name) const { auto search = channel_proto_desc_map_.find(channel_name); if (search != channel_proto_desc_map_.end()) { return search->second; } return kEmptyString; } std::set<std::string> RecordWriter::GetChannelList() const { std::set<std::string> channel_list; for (const auto& item : channel_message_number_map_) { channel_list.insert(item.first); } return channel_list; } } // namespace record } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/record/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "record", deps = [ ":record_reader", ":record_viewer", ":record_writer", ], alwayslink = True, ) cc_library( name = "record_file_base", srcs = ["file/record_file_base.cc"], hdrs = ["file/record_file_base.h"], deps = [ "//cyber/common:log", "//cyber/proto:record_cc_proto", ], ) cc_library( name = "record_file_reader", srcs = ["file/record_file_reader.cc"], hdrs = ["file/record_file_reader.h"], deps = [ ":record_file_base", ":section", "//cyber/common:file", "//cyber/time", "@com_google_protobuf//:protobuf", ], ) cc_library( name = "record_file_writer", srcs = ["file/record_file_writer.cc"], hdrs = ["file/record_file_writer.h"], deps = [ ":record_file_base", ":section", "//cyber/common:file", "//cyber/time", "@com_google_protobuf//:protobuf", ], ) cc_library( name = "section", hdrs = ["file/section.h"], ) cc_test( name = "record_file_test", size = "small", srcs = ["file/record_file_test.cc"], deps = [ "//cyber", "//cyber/proto:record_cc_proto", "@com_google_googletest//:gtest_main", ], ) cc_test( name = "record_file_integration_test", size = "small", srcs = ["file/record_file_integration_test.cc"], tags = [ "cpu:3", "exclusive", "manual", ], deps = [ "//cyber", "//cyber/proto:record_cc_proto", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "header_builder", srcs = ["header_builder.cc"], hdrs = ["header_builder.h"], deps = [ "//cyber/proto:record_cc_proto", ], ) cc_library( name = "record_base", hdrs = ["record_base.h"], deps = [ "//cyber/proto:record_cc_proto", ], ) cc_library( name = "record_message", hdrs = ["record_message.h"], ) cc_library( name = "record_reader", srcs = ["record_reader.cc"], hdrs = ["record_reader.h"], deps = [ ":record_base", ":record_file_reader", ":record_message", ], alwayslink = True, ) cc_test( name = "record_reader_test", size = "small", srcs = ["record_reader_test.cc"], deps = [ "//cyber", "//cyber/proto:record_cc_proto", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "record_viewer", srcs = ["record_viewer.cc"], hdrs = ["record_viewer.h"], deps = [ ":record_message", ":record_reader", ], alwayslink = True, ) cc_test( name = "record_viewer_test", size = "small", srcs = ["record_viewer_test.cc"], deps = [ "//cyber", "//cyber/proto:record_cc_proto", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "record_writer", srcs = ["record_writer.cc"], hdrs = ["record_writer.h"], deps = [ ":header_builder", ":record_base", ":record_file_writer", "//cyber/message:message_traits", "//cyber/message:raw_message", "//cyber/proto:record_cc_proto", ], alwayslink = True, ) cpplint()
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/record/header_builder.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef CYBER_RECORD_HEADER_BUILDER_H_ #define CYBER_RECORD_HEADER_BUILDER_H_ #include "cyber/proto/record.pb.h" namespace apollo { namespace cyber { namespace record { /** * @brief The builder of record header. */ class HeaderBuilder { public: /** * @brief Build a record header with customized max interval time (ns) and max * raw size (byte) for segment. * * @param segment_interval * @param segment_raw_size * * @return A customized record header. */ static proto::Header GetHeaderWithSegmentParams( const uint64_t segment_interval, const uint64_t segment_raw_size); /** * @brief Build a record header with customized max interval time (ns) and max * raw size (byte) for chunk. * * @param chunk_interval * @param chunk_raw_size * * @return A customized record header. */ static proto::Header GetHeaderWithChunkParams(const uint64_t chunk_interval, const uint64_t chunk_raw_size); /** * @brief Build a default record header. * * @return A default record header. */ static proto::Header GetHeader(); private: static const uint32_t MAJOR_VERSION_ = 1; static const uint32_t MINOR_VERSION_ = 0; static const proto::CompressType COMPRESS_TYPE_ = proto::CompressType::COMPRESS_NONE; static const uint64_t CHUNK_INTERVAL_ = 20 * 1000 * 1000 * 1000ULL; // 20s static const uint64_t SEGMENT_INTERVAL_ = 60 * 1000 * 1000 * 1000ULL; // 60s static const uint64_t CHUNK_RAW_SIZE_ = 200 * 1024 * 1024ULL; // 200MB static const uint64_t SEGMENT_RAW_SIZE_ = 2048 * 1024 * 1024ULL; // 2GB }; } // namespace record } // namespace cyber } // namespace apollo #endif // CYBER_RECORD_HEADER_BUILDER_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/record/record_writer.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef CYBER_RECORD_RECORD_WRITER_H_ #define CYBER_RECORD_RECORD_WRITER_H_ #include <cstdint> #include <memory> #include <mutex> #include <set> #include <sstream> #include <string> #include <unordered_map> #include "cyber/proto/record.pb.h" #include "cyber/common/log.h" #include "cyber/message/message_traits.h" #include "cyber/message/raw_message.h" #include "cyber/record/file/record_file_writer.h" #include "cyber/record/header_builder.h" #include "cyber/record/record_base.h" namespace apollo { namespace cyber { namespace record { /** * @brief The record writer. */ class RecordWriter : public RecordBase { public: using MessageNumberMap = std::unordered_map<std::string, uint64_t>; using MessageTypeMap = std::unordered_map<std::string, std::string>; using MessageProtoDescMap = std::unordered_map<std::string, std::string>; using FileWriterPtr = std::unique_ptr<RecordFileWriter>; /** * @brief The default constructor. */ RecordWriter(); /** * @brief The constructor with record header as parameter. * * @param header */ explicit RecordWriter(const proto::Header& header); /** * @brief Virtual Destructor. */ virtual ~RecordWriter(); /** * @brief Open a record to write. * * @param file * * @return True for success, false for fail. */ bool Open(const std::string& file); /** * @brief Clean the record. */ void Close(); /** * @brief Write a channel to record. * * @param channel_name * @param message_type * @param proto_desc * * @return True for success, false for fail. */ bool WriteChannel(const std::string& channel_name, const std::string& message_type, const std::string& proto_desc); /** * @brief Write a message to record. * * @tparam MessageT * @param channel_name * @param message * @param time_nanosec * @param proto_desc * * @return True for success, false for fail. */ template <typename MessageT> bool WriteMessage(const std::string& channel_name, const MessageT& message, const uint64_t time_nanosec, const std::string& proto_desc = ""); /** * @brief Set max size (KB) to segment record file * * @param size_kilobytes * * @return True for success, false for fail. */ bool SetSizeOfFileSegmentation(uint64_t size_kilobytes); /** * @brief Set max interval (Second) to segment record file. * * @param time_sec * * @return True for success, false for fail. */ bool SetIntervalOfFileSegmentation(uint64_t time_sec); /** * @brief Get message number by channel name. * * @param channel_name * * @return Message number. */ uint64_t GetMessageNumber(const std::string& channel_name) const override; /** * @brief Get message type by channel name. * * @param channel_name * * @return Message type. */ const std::string& GetMessageType( const std::string& channel_name) const override; /** * @brief Get proto descriptor string by channel name. * * @param channel_name * * @return Proto descriptor string by channel name. */ const std::string& GetProtoDesc( const std::string& channel_name) const override; /** * @brief Get channel list. * * @return List container with all channel name string. */ std::set<std::string> GetChannelList() const override; /** * @brief Is a new channel recording or not. * * @return True for yes, false for no. */ bool IsNewChannel(const std::string& channel_name) const; private: bool WriteMessage(const proto::SingleMessage& single_msg); bool SplitOutfile(); void OnNewChannel(const std::string& channel_name, const std::string& message_type, const std::string& proto_desc); void OnNewMessage(const std::string& channel_name); std::string path_; uint64_t segment_raw_size_ = 0; uint64_t segment_begin_time_ = 0; uint32_t file_index_ = 0; MessageNumberMap channel_message_number_map_; MessageTypeMap channel_message_type_map_; MessageProtoDescMap channel_proto_desc_map_; FileWriterPtr file_writer_ = nullptr; FileWriterPtr file_writer_backup_ = nullptr; std::mutex mutex_; std::stringstream sstream_; }; template <> inline bool RecordWriter::WriteMessage(const std::string& channel_name, const std::string& message, const uint64_t time_nanosec, const std::string& proto_desc) { proto::SingleMessage single_msg; single_msg.set_channel_name(channel_name); single_msg.set_content(message); single_msg.set_time(time_nanosec); return WriteMessage(single_msg); } template <> inline bool RecordWriter::WriteMessage( const std::string& channel_name, const std::shared_ptr<message::RawMessage>& message, const uint64_t time_nanosec, const std::string& proto_desc) { if (message == nullptr) { AERROR << "nullptr error, channel: " << channel_name; return false; } return WriteMessage(channel_name, message->message, time_nanosec); } template <typename MessageT> bool RecordWriter::WriteMessage(const std::string& channel_name, const MessageT& message, const uint64_t time_nanosec, const std::string& proto_desc) { const std::string& message_type = GetMessageType(channel_name); if (message_type.empty()) { if (!WriteChannel(channel_name, message::GetMessageName<MessageT>(), proto_desc)) { AERROR << "Failed to write meta data to channel [" << channel_name << "]."; return false; } } else { if (MessageT::descriptor()->full_name() != message_type) { AERROR << "Message type is invalid, expect: " << message_type << ", actual: " << message::GetMessageName<MessageT>(); return false; } } std::string content(""); if (!message.SerializeToString(&content)) { AERROR << "Failed to serialize message, channel: " << channel_name; return false; } return WriteMessage(channel_name, content, time_nanosec); } } // namespace record } // namespace cyber } // namespace apollo #endif // CYBER_RECORD_RECORD_WRITER_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/record/record_base.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef CYBER_RECORD_RECORD_BASE_H_ #define CYBER_RECORD_RECORD_BASE_H_ #include <cstdint> #include <set> #include <string> #include "cyber/proto/record.pb.h" namespace apollo { namespace cyber { namespace record { static const std::string& kEmptyString = ""; /** * @brief Base class for record reader and writer. */ class RecordBase { public: /** * @brief Destructor. */ virtual ~RecordBase() = default; /** * @brief Get message number by channel name. * * @param channel_name * * @return Message number. */ virtual uint64_t GetMessageNumber(const std::string& channel_name) const = 0; /** * @brief Get message type by channel name. * * @param channel_name * * @return Message type. */ virtual const std::string& GetMessageType( const std::string& channel_name) const = 0; /** * @brief Get proto descriptor string by channel name. * * @param channel_name * * @return Proto descriptor string by channel name. */ virtual const std::string& GetProtoDesc( const std::string& channel_name) const = 0; /** * @brief Get channel list. * * @return List container with all channel name string. */ virtual std::set<std::string> GetChannelList() const = 0; /** * @brief Get record header. * * @return Record header. */ const proto::Header& GetHeader() const { return header_; } /** * @brief Get record file path. * * @return Record file path. */ const std::string GetFile() const { return file_; } protected: std::string file_; proto::Header header_; bool is_opened_ = false; }; } // namespace record } // namespace cyber } // namespace apollo #endif // CYBER_RECORD_RECORD_BASE_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/record/header_builder.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/record/header_builder.h" namespace apollo { namespace cyber { namespace record { using ::apollo::cyber::proto::CompressType; proto::Header HeaderBuilder::GetHeader() { proto::Header header; header.set_major_version(MAJOR_VERSION_); header.set_minor_version(MINOR_VERSION_); header.set_compress(COMPRESS_TYPE_); header.set_chunk_interval(CHUNK_INTERVAL_); header.set_segment_interval(SEGMENT_INTERVAL_); header.set_index_position(0); header.set_chunk_number(0); header.set_channel_number(0); header.set_begin_time(0); header.set_end_time(0); header.set_message_number(0); header.set_size(0); header.set_is_complete(false); header.set_chunk_raw_size(CHUNK_RAW_SIZE_); header.set_segment_raw_size(SEGMENT_RAW_SIZE_); return header; } proto::Header HeaderBuilder::GetHeaderWithSegmentParams( const uint64_t segment_interval, const uint64_t segment_raw_size) { proto::Header header; header.set_major_version(MAJOR_VERSION_); header.set_minor_version(MINOR_VERSION_); header.set_compress(COMPRESS_TYPE_); header.set_chunk_interval(CHUNK_INTERVAL_); header.set_chunk_raw_size(CHUNK_RAW_SIZE_); header.set_index_position(0); header.set_chunk_number(0); header.set_channel_number(0); header.set_begin_time(0); header.set_end_time(0); header.set_message_number(0); header.set_size(0); header.set_is_complete(false); header.set_segment_raw_size(segment_raw_size); header.set_segment_interval(segment_interval); return header; } proto::Header HeaderBuilder::GetHeaderWithChunkParams( const uint64_t chunk_interval, const uint64_t chunk_raw_size) { proto::Header header; header.set_major_version(MAJOR_VERSION_); header.set_minor_version(MINOR_VERSION_); header.set_compress(COMPRESS_TYPE_); header.set_segment_interval(SEGMENT_INTERVAL_); header.set_segment_raw_size(SEGMENT_RAW_SIZE_); header.set_index_position(0); header.set_chunk_number(0); header.set_channel_number(0); header.set_begin_time(0); header.set_end_time(0); header.set_message_number(0); header.set_size(0); header.set_is_complete(false); header.set_chunk_interval(chunk_interval); header.set_chunk_raw_size(chunk_raw_size); return header; } } // namespace record } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/record
apollo_public_repos/apollo/cyber/record/file/record_file_reader.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef CYBER_RECORD_FILE_RECORD_FILE_READER_H_ #define CYBER_RECORD_FILE_RECORD_FILE_READER_H_ #include <fstream> #include <memory> #include <string> #include <unordered_map> #include <utility> #include <limits> #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/io/zero_copy_stream_impl.h" #include "google/protobuf/message.h" #include "google/protobuf/text_format.h" #include "cyber/common/log.h" #include "cyber/record/file/record_file_base.h" #include "cyber/record/file/section.h" #include "cyber/time/time.h" namespace apollo { namespace cyber { namespace record { using google::protobuf::io::CodedInputStream; using google::protobuf::io::FileInputStream; using google::protobuf::io::ZeroCopyInputStream; class RecordFileReader : public RecordFileBase { public: RecordFileReader() = default; virtual ~RecordFileReader(); bool Open(const std::string& path) override; void Close() override; bool Reset(); bool ReadSection(Section* section); bool SkipSection(int64_t size); template <typename T> bool ReadSection(int64_t size, T* message); bool ReadIndex(); bool EndOfFile() { return end_of_file_; } private: bool ReadHeader(); bool end_of_file_ = false; }; template <typename T> bool RecordFileReader::ReadSection(int64_t size, T* message) { if (size < std::numeric_limits<int>::min() || size > std::numeric_limits<int>::max()) { AERROR << "Size value greater than the range of int value."; return false; } FileInputStream raw_input(fd_, static_cast<int>(size)); CodedInputStream coded_input(&raw_input); CodedInputStream::Limit limit = coded_input.PushLimit(static_cast<int>(size)); if (!message->ParseFromCodedStream(&coded_input)) { AERROR << "Parse section message failed."; end_of_file_ = coded_input.ExpectAtEnd(); return false; } if (!coded_input.ConsumedEntireMessage()) { AERROR << "Do not consumed entire message."; return false; } coded_input.PopLimit(limit); if (static_cast<int64_t>(message->ByteSizeLong()) != size) { AERROR << "Message size is not consistent in section header" << ", expect: " << size << ", actual: " << message->ByteSizeLong(); return false; } return true; } } // namespace record } // namespace cyber } // namespace apollo #endif // CYBER_RECORD_FILE_RECORD_FILE_READER_H_
0
apollo_public_repos/apollo/cyber/record
apollo_public_repos/apollo/cyber/record/file/record_file_base.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef CYBER_RECORD_FILE_RECORD_FILE_BASE_H_ #define CYBER_RECORD_FILE_RECORD_FILE_BASE_H_ #include <mutex> #include <string> #include "cyber/proto/record.pb.h" namespace apollo { namespace cyber { namespace record { const int HEADER_LENGTH = 2048; class RecordFileBase { public: RecordFileBase() = default; virtual ~RecordFileBase() = default; virtual bool Open(const std::string& path) = 0; virtual void Close() = 0; const std::string& GetPath() const { return path_; } const proto::Header& GetHeader() const { return header_; } const proto::Index& GetIndex() const { return index_; } int64_t CurrentPosition(); bool SetPosition(int64_t position); protected: std::mutex mutex_; std::string path_; proto::Header header_; proto::Index index_; int fd_ = -1; }; } // namespace record } // namespace cyber } // namespace apollo #endif // CYBER_RECORD_FILE_RECORD_FILE_BASE_H_
0
apollo_public_repos/apollo/cyber/record
apollo_public_repos/apollo/cyber/record/file/record_file_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include <unistd.h> #include <atomic> #include <string> #include "gflags/gflags.h" #include "gtest/gtest.h" #include "cyber/record/file/record_file_base.h" #include "cyber/record/file/record_file_reader.h" #include "cyber/record/file/record_file_writer.h" #include "cyber/record/header_builder.h" namespace apollo { namespace cyber { namespace record { using apollo::cyber::proto::Channel; using apollo::cyber::proto::ChunkBody; using apollo::cyber::proto::ChunkHeader; using apollo::cyber::proto::Header; using apollo::cyber::proto::SectionType; using apollo::cyber::proto::SingleMessage; constexpr char kChan1[] = "/test1"; constexpr char kChan2[] = "/test2"; constexpr char kMsgType[] = "apollo.cyber.proto.Test"; constexpr char kStr10B[] = "1234567890"; constexpr char kTestFile1[] = "record_file_test_1.record"; constexpr char kTestFile2[] = "record_file_test_2.record"; TEST(ChunkTest, TestAll) { Chunk ck; ASSERT_EQ(0, ck.header_.begin_time()); ASSERT_EQ(0, ck.header_.end_time()); ASSERT_EQ(0, ck.header_.raw_size()); ASSERT_EQ(0, ck.header_.message_number()); ASSERT_TRUE(ck.empty()); SingleMessage msg1; msg1.set_channel_name(kChan1); msg1.set_content(kStr10B); msg1.set_time(1e9); ck.add(msg1); ASSERT_EQ(1e9, ck.header_.begin_time()); ASSERT_EQ(1e9, ck.header_.end_time()); ASSERT_EQ(10, ck.header_.raw_size()); ASSERT_EQ(1, ck.header_.message_number()); ASSERT_FALSE(ck.empty()); SingleMessage msg2; msg2.set_channel_name(kChan2); msg2.set_content(kStr10B); msg2.set_time(2e9); ck.add(msg2); ASSERT_EQ(1e9, ck.header_.begin_time()); ASSERT_EQ(2e9, ck.header_.end_time()); ASSERT_EQ(20, ck.header_.raw_size()); ASSERT_EQ(2, ck.header_.message_number()); ASSERT_FALSE(ck.empty()); ck.clear(); ASSERT_EQ(0, ck.header_.begin_time()); ASSERT_EQ(0, ck.header_.end_time()); ASSERT_EQ(0, ck.header_.raw_size()); ASSERT_EQ(0, ck.header_.message_number()); ASSERT_TRUE(ck.empty()); } TEST(RecordFileTest, TestOneMessageFile) { // writer open one message file RecordFileWriter rfw; ASSERT_TRUE(rfw.Open(kTestFile1)); ASSERT_EQ(kTestFile1, rfw.GetPath()); // write header section Header hdr1 = HeaderBuilder::GetHeaderWithSegmentParams(0, 0); hdr1.set_chunk_interval(0); hdr1.set_chunk_raw_size(0); ASSERT_TRUE(rfw.WriteHeader(hdr1)); ASSERT_FALSE(rfw.GetHeader().is_complete()); // write channel section Channel chan1; chan1.set_name(kChan1); chan1.set_message_type(kMsgType); chan1.set_proto_desc(kStr10B); ASSERT_TRUE(rfw.WriteChannel(chan1)); // write chunk section SingleMessage msg1; msg1.set_channel_name(chan1.name()); msg1.set_content(kStr10B); msg1.set_time(1e9); ASSERT_TRUE(rfw.WriteMessage(msg1)); ASSERT_EQ(1, rfw.GetMessageNumber(chan1.name())); // writer close one message file rfw.Close(); ASSERT_TRUE(rfw.GetHeader().is_complete()); ASSERT_EQ(1, rfw.GetHeader().chunk_number()); ASSERT_EQ(1e9, rfw.GetHeader().begin_time()); ASSERT_EQ(1e9, rfw.GetHeader().end_time()); ASSERT_EQ(1, rfw.GetHeader().message_number()); hdr1 = rfw.GetHeader(); // header open one message file RecordFileReader rfr; ASSERT_TRUE(rfr.Open(kTestFile1)); ASSERT_EQ(kTestFile1, rfr.GetPath()); Section sec; // read header section Header hdr2 = rfr.GetHeader(); ASSERT_EQ(hdr2.chunk_number(), hdr1.chunk_number()); ASSERT_EQ(hdr2.begin_time(), hdr1.begin_time()); ASSERT_EQ(hdr2.end_time(), hdr1.end_time()); ASSERT_EQ(hdr2.message_number(), hdr1.message_number()); // read channel section ASSERT_TRUE(rfr.ReadSection(&sec)); ASSERT_EQ(SectionType::SECTION_CHANNEL, sec.type); Channel chan2; ASSERT_TRUE(rfr.ReadSection<Channel>(sec.size, &chan2)); ASSERT_EQ(chan2.name(), chan1.name()); ASSERT_EQ(chan2.message_type(), chan1.message_type()); ASSERT_EQ(chan2.proto_desc(), chan1.proto_desc()); // read chunk header section ASSERT_TRUE(rfr.ReadSection(&sec)); ASSERT_EQ(SectionType::SECTION_CHUNK_HEADER, sec.type); ChunkHeader ckh2; ASSERT_TRUE(rfr.ReadSection<ChunkHeader>(sec.size, &ckh2)); ASSERT_EQ(ckh2.begin_time(), 1e9); ASSERT_EQ(ckh2.end_time(), 1e9); ASSERT_EQ(ckh2.raw_size(), 10); ASSERT_EQ(ckh2.message_number(), 1); // read chunk body section ASSERT_TRUE(rfr.ReadSection(&sec)); ASSERT_EQ(SectionType::SECTION_CHUNK_BODY, sec.type); ChunkBody ckb2; ASSERT_TRUE(rfr.ReadSection<ChunkBody>(sec.size, &ckb2)); ASSERT_EQ(ckb2.messages_size(), 1); ASSERT_EQ(ckb2.messages(0).channel_name(), ckb2.messages(0).channel_name()); ASSERT_EQ(ckb2.messages(0).time(), ckb2.messages(0).time()); ASSERT_EQ(ckb2.messages(0).content(), ckb2.messages(0).content()); ASSERT_FALSE(remove(kTestFile1)); } TEST(RecordFileTest, TestOneChunkFile) { RecordFileWriter rfw; ASSERT_TRUE(rfw.Open(kTestFile1)); ASSERT_EQ(kTestFile1, rfw.GetPath()); Header header = HeaderBuilder::GetHeaderWithChunkParams(0, 0); header.set_segment_interval(0); header.set_segment_raw_size(0); ASSERT_TRUE(rfw.WriteHeader(header)); ASSERT_FALSE(rfw.GetHeader().is_complete()); Channel chan1; chan1.set_name(kChan1); chan1.set_message_type(kMsgType); chan1.set_proto_desc(kStr10B); ASSERT_TRUE(rfw.WriteChannel(chan1)); Channel chan2; chan2.set_name(kChan2); chan2.set_message_type(kMsgType); chan2.set_proto_desc(kStr10B); ASSERT_TRUE(rfw.WriteChannel(chan2)); SingleMessage msg1; msg1.set_channel_name(chan1.name()); msg1.set_content(kStr10B); msg1.set_time(1e9); ASSERT_TRUE(rfw.WriteMessage(msg1)); ASSERT_EQ(1, rfw.GetMessageNumber(chan1.name())); SingleMessage msg2; msg2.set_channel_name(chan2.name()); msg2.set_content(kStr10B); msg2.set_time(2e9); ASSERT_TRUE(rfw.WriteMessage(msg2)); ASSERT_EQ(1, rfw.GetMessageNumber(chan2.name())); SingleMessage msg3; msg3.set_channel_name(chan1.name()); msg3.set_content(kStr10B); msg3.set_time(3e9); ASSERT_TRUE(rfw.WriteMessage(msg3)); ASSERT_EQ(2, rfw.GetMessageNumber(chan1.name())); rfw.Close(); ASSERT_TRUE(rfw.GetHeader().is_complete()); ASSERT_EQ(1, rfw.GetHeader().chunk_number()); ASSERT_EQ(1e9, rfw.GetHeader().begin_time()); ASSERT_EQ(3e9, rfw.GetHeader().end_time()); ASSERT_EQ(3, rfw.GetHeader().message_number()); ASSERT_FALSE(remove(kTestFile1)); } TEST(RecordFileTest, TestIndex) { { RecordFileWriter* rfw = new RecordFileWriter(); ASSERT_TRUE(rfw->Open(kTestFile2)); ASSERT_EQ(kTestFile2, rfw->GetPath()); Header header = HeaderBuilder::GetHeaderWithChunkParams(0, 0); header.set_segment_interval(0); header.set_segment_raw_size(0); ASSERT_TRUE(rfw->WriteHeader(header)); ASSERT_FALSE(rfw->GetHeader().is_complete()); Channel chan1; chan1.set_name(kChan1); chan1.set_message_type(kMsgType); chan1.set_proto_desc(kStr10B); ASSERT_TRUE(rfw->WriteChannel(chan1)); Channel chan2; chan2.set_name(kChan2); chan2.set_message_type(kMsgType); chan2.set_proto_desc(kStr10B); ASSERT_TRUE(rfw->WriteChannel(chan2)); SingleMessage msg1; msg1.set_channel_name(chan1.name()); msg1.set_content(kStr10B); msg1.set_time(1e9); ASSERT_TRUE(rfw->WriteMessage(msg1)); ASSERT_EQ(1, rfw->GetMessageNumber(chan1.name())); SingleMessage msg2; msg2.set_channel_name(chan2.name()); msg2.set_content(kStr10B); msg2.set_time(2e9); ASSERT_TRUE(rfw->WriteMessage(msg2)); ASSERT_EQ(1, rfw->GetMessageNumber(chan2.name())); SingleMessage msg3; msg3.set_channel_name(chan1.name()); msg3.set_content(kStr10B); msg3.set_time(3e9); ASSERT_TRUE(rfw->WriteMessage(msg3)); ASSERT_EQ(2, rfw->GetMessageNumber(chan1.name())); rfw->Close(); ASSERT_TRUE(rfw->GetHeader().is_complete()); ASSERT_EQ(1, rfw->GetHeader().chunk_number()); ASSERT_EQ(1e9, rfw->GetHeader().begin_time()); ASSERT_EQ(3e9, rfw->GetHeader().end_time()); ASSERT_EQ(3, rfw->GetHeader().message_number()); } { RecordFileReader reader; reader.Open(kTestFile2); reader.ReadIndex(); const auto& index = reader.GetIndex(); // Walk through file the long way and check that the indexes match the // sections reader.Reset(); Section section; for (uint64_t pos = reader.CurrentPosition(); reader.ReadSection(&section) && reader.SkipSection(section.size); pos = reader.CurrentPosition()) { // Find index at position if (section.type != SectionType::SECTION_INDEX) { bool found = false; proto::SingleIndex match; for (const auto& row : index.indexes()) { if (row.position() == pos) { match = row; found = true; break; } } ASSERT_TRUE(found); EXPECT_EQ(match.position(), pos); EXPECT_EQ(match.type(), section.type); } } } } } // namespace record } // namespace cyber } // namespace apollo int main(int argc, char** argv) { testing::GTEST_FLAG(catch_exceptions) = 1; testing::InitGoogleTest(&argc, argv); google::InitGoogleLogging(argv[0]); FLAGS_logtostderr = true; const int ret_val = RUN_ALL_TESTS(); google::protobuf::ShutdownProtobufLibrary(); google::ShutDownCommandLineFlags(); return ret_val; }
0
apollo_public_repos/apollo/cyber/record
apollo_public_repos/apollo/cyber/record/file/section.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef CYBER_RECORD_FILE_SECTION_H_ #define CYBER_RECORD_FILE_SECTION_H_ namespace apollo { namespace cyber { namespace record { struct Section { proto::SectionType type; int64_t size; }; } // namespace record } // namespace cyber } // namespace apollo #endif // CYBER_RECORD_FILE_SECTION_H_
0
apollo_public_repos/apollo/cyber/record
apollo_public_repos/apollo/cyber/record/file/record_file_reader.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/record/file/record_file_reader.h" #include "cyber/common/file.h" namespace apollo { namespace cyber { namespace record { using apollo::cyber::proto::SectionType; bool RecordFileReader::Open(const std::string& path) { std::lock_guard<std::mutex> lock(mutex_); path_ = path; if (!::apollo::cyber::common::PathExists(path_)) { AERROR << "File not exist, file: " << path_; return false; } fd_ = open(path_.data(), O_RDONLY); if (fd_ < 0) { AERROR << "Open file failed, file: " << path_ << ", fd: " << fd_ << ", errno: " << errno; return false; } end_of_file_ = false; if (!ReadHeader()) { AERROR << "Read header section fail, file: " << path_; return false; } return true; } void RecordFileReader::Close() { if (fd_ >= 0) { close(fd_); fd_ = -1; } } bool RecordFileReader::Reset() { if (!SetPosition(sizeof(struct Section) + HEADER_LENGTH)) { AERROR << "Reset position fail, file: " << path_; return false; } end_of_file_ = false; return true; } bool RecordFileReader::ReadHeader() { Section section; if (!ReadSection(&section)) { AERROR << "Read header section fail, file is broken or it is not a record " "file."; return false; } if (section.type != SectionType::SECTION_HEADER) { AERROR << "Check section type failed" << ", expect: " << SectionType::SECTION_HEADER << ", actual: " << section.type; return false; } if (!ReadSection<proto::Header>(section.size, &header_)) { AERROR << "Read header section fail, file is broken or it is not a record " "file."; return false; } if (!SetPosition(sizeof(struct Section) + HEADER_LENGTH)) { AERROR << "Skip bytes for reaching the nex section failed."; return false; } return true; } bool RecordFileReader::ReadIndex() { if (!header_.is_complete()) { AERROR << "Record file is not complete."; return false; } if (!SetPosition(header_.index_position())) { AERROR << "Skip bytes for reaching the index section failed."; return false; } Section section; if (!ReadSection(&section)) { AERROR << "Read index section fail, maybe file is broken."; return false; } if (section.type != SectionType::SECTION_INDEX) { AERROR << "Check section type failed" << ", expect: " << SectionType::SECTION_INDEX << ", actual: " << section.type; return false; } if (!ReadSection<proto::Index>(section.size, &index_)) { AERROR << "Read index section fail."; return false; } Reset(); return true; } bool RecordFileReader::ReadSection(Section* section) { ssize_t count = read(fd_, section, sizeof(struct Section)); if (count < 0) { AERROR << "Read fd failed, fd_: " << fd_ << ", errno: " << errno; return false; } else if (count == 0) { end_of_file_ = true; AINFO << "Reach end of file."; return false; } else if (count != sizeof(struct Section)) { AERROR << "Read fd failed, fd_: " << fd_ << ", expect count: " << sizeof(struct Section) << ", actual count: " << count; return false; } return true; } bool RecordFileReader::SkipSection(int64_t size) { int64_t pos = CurrentPosition(); if (size > INT64_MAX - pos) { AERROR << "Current position plus skip count is larger than INT64_MAX, " << pos << " + " << size << " > " << INT64_MAX; return false; } if (!SetPosition(pos + size)) { AERROR << "Skip failed, file: " << path_ << ", current position: " << pos << "skip count: " << size; return false; } return true; } RecordFileReader::~RecordFileReader() { Close(); } } // namespace record } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/record
apollo_public_repos/apollo/cyber/record/file/record_file_writer.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/record/file/record_file_writer.h" #include <fcntl.h> #include "cyber/common/file.h" #include "cyber/time/time.h" namespace apollo { namespace cyber { namespace record { using apollo::cyber::proto::Channel; using apollo::cyber::proto::ChannelCache; using apollo::cyber::proto::ChunkBody; using apollo::cyber::proto::ChunkBodyCache; using apollo::cyber::proto::ChunkHeader; using apollo::cyber::proto::ChunkHeaderCache; using apollo::cyber::proto::Header; using apollo::cyber::proto::SectionType; using apollo::cyber::proto::SingleIndex; RecordFileWriter::RecordFileWriter() : is_writing_(false) {} RecordFileWriter::~RecordFileWriter() { Close(); } bool RecordFileWriter::Open(const std::string& path) { std::lock_guard<std::mutex> lock(mutex_); path_ = path; if (::apollo::cyber::common::PathExists(path_)) { AWARN << "File exist and overwrite, file: " << path_; } fd_ = open(path_.data(), O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (fd_ < 0) { AERROR << "Open file failed, file: " << path_ << ", fd: " << fd_ << ", errno: " << errno; return false; } chunk_active_.reset(new Chunk()); chunk_flush_.reset(new Chunk()); is_writing_ = true; flush_thread_ = std::make_shared<std::thread>([this]() { this->Flush(); }); if (flush_thread_ == nullptr) { AERROR << "Init flush thread error."; return false; } return true; } void RecordFileWriter::Close() { if (is_writing_) { // wait for the flush operation that may exist now while (1) { { std::unique_lock<std::mutex> flush_lock(flush_mutex_); if (chunk_flush_->empty()) { break; } } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } // last swap { std::unique_lock<std::mutex> flush_lock(flush_mutex_); chunk_flush_.swap(chunk_active_); flush_cv_.notify_one(); } // wait for the last flush operation while (1) { { std::unique_lock<std::mutex> flush_lock(flush_mutex_); if (chunk_flush_->empty()) { break; } } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } is_writing_ = false; flush_cv_.notify_all(); if (flush_thread_ && flush_thread_->joinable()) { flush_thread_->join(); flush_thread_ = nullptr; } if (!WriteIndex()) { AERROR << "Write index section failed, file: " << path_; } header_.set_is_complete(true); if (!WriteHeader(header_)) { AERROR << "Overwrite header section failed, file: " << path_; } if (close(fd_) < 0) { AERROR << "Close file failed, file: " << path_ << ", fd: " << fd_ << ", errno: " << errno; } } } bool RecordFileWriter::WriteHeader(const Header& header) { std::lock_guard<std::mutex> lock(mutex_); header_ = header; if (!WriteSection<Header>(header_)) { AERROR << "Write header section fail"; return false; } return true; } bool RecordFileWriter::WriteIndex() { std::lock_guard<std::mutex> lock(mutex_); for (int i = 0; i < index_.indexes_size(); i++) { SingleIndex* single_index = index_.mutable_indexes(i); if (single_index->type() == SectionType::SECTION_CHANNEL) { ChannelCache* channel_cache = single_index->mutable_channel_cache(); if (channel_message_number_map_.find(channel_cache->name()) != channel_message_number_map_.end()) { channel_cache->set_message_number( channel_message_number_map_[channel_cache->name()]); } } } header_.set_index_position(CurrentPosition()); if (!WriteSection<proto::Index>(index_)) { AERROR << "Write section fail"; return false; } return true; } bool RecordFileWriter::WriteChannel(const Channel& channel) { std::lock_guard<std::mutex> lock(mutex_); uint64_t pos = CurrentPosition(); if (!WriteSection<Channel>(channel)) { AERROR << "Write section fail"; return false; } header_.set_channel_number(header_.channel_number() + 1); SingleIndex* single_index = index_.add_indexes(); single_index->set_type(SectionType::SECTION_CHANNEL); single_index->set_position(pos); ChannelCache* channel_cache = new ChannelCache(); channel_cache->set_name(channel.name()); channel_cache->set_message_number(0); channel_cache->set_message_type(channel.message_type()); channel_cache->set_proto_desc(channel.proto_desc()); single_index->set_allocated_channel_cache(channel_cache); return true; } bool RecordFileWriter::WriteChunk(const ChunkHeader& chunk_header, const ChunkBody& chunk_body) { std::lock_guard<std::mutex> lock(mutex_); uint64_t pos = CurrentPosition(); if (!WriteSection<ChunkHeader>(chunk_header)) { AERROR << "Write chunk header fail"; return false; } SingleIndex* single_index = index_.add_indexes(); single_index->set_type(SectionType::SECTION_CHUNK_HEADER); single_index->set_position(pos); ChunkHeaderCache* chunk_header_cache = new ChunkHeaderCache(); chunk_header_cache->set_begin_time(chunk_header.begin_time()); chunk_header_cache->set_end_time(chunk_header.end_time()); chunk_header_cache->set_message_number(chunk_header.message_number()); chunk_header_cache->set_raw_size(chunk_header.raw_size()); single_index->set_allocated_chunk_header_cache(chunk_header_cache); pos = CurrentPosition(); if (!WriteSection<ChunkBody>(chunk_body)) { AERROR << "Write chunk body fail"; return false; } header_.set_chunk_number(header_.chunk_number() + 1); if (header_.begin_time() == 0) { header_.set_begin_time(chunk_header.begin_time()); } header_.set_end_time(chunk_header.end_time()); header_.set_message_number(header_.message_number() + chunk_header.message_number()); single_index = index_.add_indexes(); single_index->set_type(SectionType::SECTION_CHUNK_BODY); single_index->set_position(pos); ChunkBodyCache* chunk_body_cache = new ChunkBodyCache(); chunk_body_cache->set_message_number(chunk_body.messages_size()); single_index->set_allocated_chunk_body_cache(chunk_body_cache); return true; } bool RecordFileWriter::WriteMessage(const proto::SingleMessage& message) { chunk_active_->add(message); auto it = channel_message_number_map_.find(message.channel_name()); if (it != channel_message_number_map_.end()) { it->second++; } else { channel_message_number_map_.insert( std::make_pair(message.channel_name(), 1)); } bool need_flush = false; if (header_.chunk_interval() > 0 && message.time() - chunk_active_->header_.begin_time() > header_.chunk_interval()) { need_flush = true; } if (header_.chunk_raw_size() > 0 && chunk_active_->header_.raw_size() > header_.chunk_raw_size()) { need_flush = true; } if (!need_flush) { return true; } { std::unique_lock<std::mutex> flush_lock(flush_mutex_); chunk_flush_.swap(chunk_active_); flush_cv_.notify_one(); } return true; } void RecordFileWriter::Flush() { while (is_writing_) { std::unique_lock<std::mutex> flush_lock(flush_mutex_); flush_cv_.wait(flush_lock, [this] { return !chunk_flush_->empty() || !is_writing_; }); if (!is_writing_) { break; } if (chunk_flush_->empty()) { continue; } if (!WriteChunk(chunk_flush_->header_, *(chunk_flush_->body_.get()))) { AERROR << "Write chunk fail."; } chunk_flush_->clear(); } } uint64_t RecordFileWriter::GetMessageNumber( const std::string& channel_name) const { auto search = channel_message_number_map_.find(channel_name); if (search != channel_message_number_map_.end()) { return search->second; } return 0; } } // namespace record } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/record
apollo_public_repos/apollo/cyber/record/file/record_file_writer.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef CYBER_RECORD_FILE_RECORD_FILE_WRITER_H_ #define CYBER_RECORD_FILE_RECORD_FILE_WRITER_H_ #include <condition_variable> #include <fstream> #include <memory> #include <string> #include <thread> #include <type_traits> #include <unordered_map> #include <utility> #include "google/protobuf/io/zero_copy_stream_impl.h" #include "google/protobuf/message.h" #include "google/protobuf/text_format.h" #include "cyber/common/log.h" #include "cyber/record/file/record_file_base.h" #include "cyber/record/file/section.h" #include "cyber/time/time.h" namespace apollo { namespace cyber { namespace record { struct Chunk { Chunk() { clear(); } inline void clear() { body_.reset(new proto::ChunkBody()); header_.set_begin_time(0); header_.set_end_time(0); header_.set_message_number(0); header_.set_raw_size(0); } inline void add(const proto::SingleMessage& message) { std::lock_guard<std::mutex> lock(mutex_); proto::SingleMessage* p_message = body_->add_messages(); *p_message = message; if (header_.begin_time() == 0) { header_.set_begin_time(message.time()); } if (header_.begin_time() > message.time()) { header_.set_begin_time(message.time()); } if (header_.end_time() < message.time()) { header_.set_end_time(message.time()); } header_.set_message_number(header_.message_number() + 1); header_.set_raw_size(header_.raw_size() + message.content().size()); } inline bool empty() { return header_.message_number() == 0; } std::mutex mutex_; proto::ChunkHeader header_; std::unique_ptr<proto::ChunkBody> body_ = nullptr; }; class RecordFileWriter : public RecordFileBase { public: RecordFileWriter(); virtual ~RecordFileWriter(); bool Open(const std::string& path) override; void Close() override; bool WriteHeader(const proto::Header& header); bool WriteChannel(const proto::Channel& channel); bool WriteMessage(const proto::SingleMessage& message); uint64_t GetMessageNumber(const std::string& channel_name) const; private: bool WriteChunk(const proto::ChunkHeader& chunk_header, const proto::ChunkBody& chunk_body); template <typename T> bool WriteSection(const T& message); bool WriteIndex(); void Flush(); std::atomic_bool is_writing_; std::unique_ptr<Chunk> chunk_active_ = nullptr; std::unique_ptr<Chunk> chunk_flush_ = nullptr; std::shared_ptr<std::thread> flush_thread_ = nullptr; std::mutex flush_mutex_; std::condition_variable flush_cv_; std::unordered_map<std::string, uint64_t> channel_message_number_map_; }; template <typename T> bool RecordFileWriter::WriteSection(const T& message) { proto::SectionType type; if (std::is_same<T, proto::ChunkHeader>::value) { type = proto::SectionType::SECTION_CHUNK_HEADER; } else if (std::is_same<T, proto::ChunkBody>::value) { type = proto::SectionType::SECTION_CHUNK_BODY; } else if (std::is_same<T, proto::Channel>::value) { type = proto::SectionType::SECTION_CHANNEL; } else if (std::is_same<T, proto::Header>::value) { type = proto::SectionType::SECTION_HEADER; if (!SetPosition(0)) { AERROR << "Jump to position #0 failed"; return false; } } else if (std::is_same<T, proto::Index>::value) { type = proto::SectionType::SECTION_INDEX; } else { AERROR << "Do not support this template typename."; return false; } Section section; /// zero out whole struct even if padded memset(&section, 0, sizeof(section)); section = {type, static_cast<int64_t>(message.ByteSizeLong())}; ssize_t count = write(fd_, &section, sizeof(section)); if (count < 0) { AERROR << "Write fd failed, fd: " << fd_ << ", errno: " << errno; return false; } if (count != sizeof(section)) { AERROR << "Write fd failed, fd: " << fd_ << ", expect count: " << sizeof(section) << ", actual count: " << count; return false; } { google::protobuf::io::FileOutputStream raw_output(fd_); message.SerializeToZeroCopyStream(&raw_output); } if (type == proto::SectionType::SECTION_HEADER) { static char blank[HEADER_LENGTH] = {'0'}; count = write(fd_, &blank, HEADER_LENGTH - message.ByteSizeLong()); if (count < 0) { AERROR << "Write fd failed, fd: " << fd_ << ", errno: " << errno; return false; } if (static_cast<size_t>(count) != HEADER_LENGTH - message.ByteSizeLong()) { AERROR << "Write fd failed, fd: " << fd_ << ", expect count: " << sizeof(section) << ", actual count: " << count; return false; } } header_.set_size(CurrentPosition()); return true; } } // namespace record } // namespace cyber } // namespace apollo #endif // CYBER_RECORD_FILE_RECORD_FILE_WRITER_H_
0
apollo_public_repos/apollo/cyber/record
apollo_public_repos/apollo/cyber/record/file/record_file_base.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/record/file/record_file_base.h" #include <sys/types.h> #include <unistd.h> #include "cyber/common/log.h" namespace apollo { namespace cyber { namespace record { int64_t RecordFileBase::CurrentPosition() { off_t pos = lseek(fd_, 0, SEEK_CUR); if (pos < 0) { AERROR << "lseek failed, file: " << path_ << ", fd: " << fd_ << ", offset: 0, whence: SEEK_CUR" << ", position: " << pos << ", errno: " << errno; } return pos; } bool RecordFileBase::SetPosition(int64_t position) { off_t pos = lseek(fd_, position, SEEK_SET); if (pos < 0) { AERROR << "lseek failed, file: " << path_ << ", fd: " << fd_ << ", offset: 0, whence: SEEK_SET" << ", position: " << pos << ", errno: " << errno; return false; } return true; } } // namespace record } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/record
apollo_public_repos/apollo/cyber/record/file/record_file_integration_test.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include <atomic> #include <chrono> #include <thread> #include "gtest/gtest.h" #include "cyber/record/file/record_file_base.h" #include "cyber/record/file/record_file_reader.h" #include "cyber/record/file/record_file_writer.h" #include "cyber/record/header_builder.h" namespace apollo { namespace cyber { namespace record { class CpuSchedulerLatency { public: CpuSchedulerLatency() : periodic_thread_([this] { this->Callback(); }) {} ~CpuSchedulerLatency() { running_ = false; periodic_thread_.join(); } std::chrono::nanoseconds GetMaxJitter() { return std::chrono::nanoseconds(max_jitter_); } int64_t GetNumSamples() { return samples_; } private: void Callback() { static constexpr std::chrono::milliseconds kSleepDuration(10); auto prev_time = std::chrono::steady_clock::now(); std::this_thread::sleep_for(kSleepDuration); while (running_) { const auto current_time = std::chrono::steady_clock::now(); const auto time_since_sleep = current_time - prev_time; const auto current_jitter = std::abs((time_since_sleep - kSleepDuration).count()); prev_time = current_time; max_jitter_ = std::max(current_jitter, max_jitter_); ++samples_; std::this_thread::sleep_for(kSleepDuration); } } std::atomic<bool> running_{true}; int64_t max_jitter_ = 0; int64_t samples_ = 0; std::thread periodic_thread_; }; const char kTestFile[] = "integration_test.record"; TEST(RecordFileTest, SmallMessageHighThroughputOKThreadJitter) { CpuSchedulerLatency cpu_jitter; RecordFileWriter rfw; ASSERT_TRUE(rfw.Open(kTestFile)); proto::Header hdr1 = HeaderBuilder::GetHeaderWithSegmentParams(0, 0); hdr1.set_chunk_interval(1000); hdr1.set_chunk_raw_size(0); ASSERT_TRUE(rfw.WriteHeader(hdr1)); ASSERT_FALSE(rfw.GetHeader().is_complete()); // write chunk section static const std::string kChannelName = "small_message"; static constexpr int kMaxIterations = 1000000000; static constexpr int64_t kMaxSamples = 1000; for (int i = 0; i < kMaxIterations && cpu_jitter.GetNumSamples() < kMaxSamples; ++i) { proto::SingleMessage msg1; msg1.set_channel_name(kChannelName); msg1.set_content("0123456789"); msg1.set_time(i); ASSERT_TRUE(rfw.WriteMessage(msg1)); ASSERT_EQ(i + 1, rfw.GetMessageNumber(kChannelName)); } EXPECT_GE(cpu_jitter.GetNumSamples(), kMaxSamples) << "This system may be to fast. Consider increasing kMaxIterations"; static constexpr int64_t kMaxJitterMS = 20; const int64_t max_cpu_jitter_ms = std::chrono::duration_cast<std::chrono::milliseconds>( cpu_jitter.GetMaxJitter()) .count(); EXPECT_LT(max_cpu_jitter_ms, kMaxJitterMS); ASSERT_FALSE(remove(kTestFile)); } } // namespace record } // namespace cyber } // namespace apollo int main(int argc, char** argv) { testing::GTEST_FLAG(catch_exceptions) = 1; testing::InitGoogleTest(&argc, argv); google::InitGoogleLogging(argv[0]); FLAGS_logtostderr = true; const int ret_val = RUN_ALL_TESTS(); google::protobuf::ShutdownProtobufLibrary(); google::ShutDownCommandLineFlags(); return ret_val; }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/proto/proto_desc.proto
syntax = "proto2"; package apollo.cyber.proto; message ProtoDesc { optional bytes desc = 1; repeated ProtoDesc dependencies = 2; }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/proto/unit_test.proto
syntax = "proto2"; package apollo.cyber.proto; message UnitTest { optional string class_name = 1; optional string case_name = 2; }; message Chatter { optional uint64 timestamp = 1; optional uint64 lidar_timestamp = 2; optional uint64 seq = 3; optional bytes content = 4; }; message ChatterBenchmark { optional uint64 stamp = 1; optional uint64 seq = 2; optional string content = 3; }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/proto/component_conf.proto
syntax = "proto2"; package apollo.cyber.proto; import "cyber/proto/qos_profile.proto"; message ReaderOption { optional string channel = 1; optional QosProfile qos_profile = 2; // depth: used to define capacity of processed messages optional uint32 pending_queue_size = 3 [default = 1]; // used to define capacity of unprocessed messages } message ComponentConfig { optional string name = 1; optional string config_file_path = 2; optional string flag_file_path = 3; repeated ReaderOption readers = 4; } message TimerComponentConfig { optional string name = 1; optional string config_file_path = 2; optional string flag_file_path = 3; optional uint32 interval = 4; // In milliseconds. }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/proto/simple.proto
syntax = "proto2"; import "modules/common_msgs/basic_msgs/header.proto"; package apollo.cyber.proto; message SimpleMessage { optional int32 integer = 1; optional string text = 2; optional apollo.common.Header header = 3; } message SimpleRepeatedMessage { repeated SimpleMessage message = 1; }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/proto/py_pb2.BUILD
load("@rules_python//python:defs.bzl", "py_library") package(default_visibility = ["//visibility:public"]) pb_deps = ["@com_google_protobuf//:protobuf_python"] py_library( name = "topology_change_py_pb2", srcs = ["topology_change_py_pb2.py"], deps = [":role_attributes_py_pb2"] ) py_library( name = "dag_conf_py_pb2", srcs = ["dag_conf_py_pb2.py"], deps = [":component_conf_py_pb2"] ) py_library( name = "proto_desc_py_pb2", srcs = ["proto_desc_py_pb2.py"], deps = pb_deps ) py_library( name = "choreography_conf_py_pb2", srcs = ["choreography_conf_py_pb2.py"], deps = pb_deps ) py_library( name = "record_py_pb2", srcs = ["record_py_pb2.py"], deps = pb_deps ) py_library( name = "component_conf_py_pb2", srcs = ["component_conf_py_pb2.py"], deps = [":qos_profile_py_pb2"] ) py_library( name = "cyber_conf_py_pb2", srcs = ["cyber_conf_py_pb2.py"], deps = [ ":scheduler_conf_py_pb2", ":transport_conf_py_pb2", ":run_mode_conf_py_pb2", ":perf_conf_py_pb2", ] ) py_library( name = "perf_conf_py_pb2", srcs = ["perf_conf_py_pb2.py"], deps = pb_deps ) py_library( name = "classic_conf_py_pb2", srcs = ["classic_conf_py_pb2.py"], deps = pb_deps ) py_library( name = "parameter_py_pb2", srcs = ["parameter_py_pb2.py"], deps = pb_deps ) py_library( name = "unit_test_py_pb2", srcs = ["unit_test_py_pb2.py"], deps = pb_deps ) py_library( name = "scheduler_conf_py_pb2", srcs = ["scheduler_conf_py_pb2.py"], deps = [ ":classic_conf_py_pb2", ":choreography_conf_py_pb2", ] ) py_library( name = "transport_conf_py_pb2", srcs = ["transport_conf_py_pb2.py"], deps = pb_deps ) py_library( name = "qos_profile_py_pb2", srcs = ["qos_profile_py_pb2.py"], deps = pb_deps ) py_library( name = "run_mode_conf_py_pb2", srcs = ["run_mode_conf_py_pb2.py"], deps = pb_deps ) py_library( name = "role_attributes_py_pb2", srcs = ["role_attributes_py_pb2.py"], deps = [ ":qos_profile_py_pb2", ] ) py_library( name = "clock_py_pb2", srcs = ["clock_py_pb2.py"], deps = pb_deps )
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/proto/perf_conf.proto
syntax = "proto2"; package apollo.cyber.proto; enum PerfType { SCHED = 1; TRANSPORT = 2; DATA_CACHE = 3; ALL = 4; } message PerfConf { optional bool enable = 1 [default = false]; optional PerfType type = 2 [default = ALL]; }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/proto/run_mode_conf.proto
syntax = "proto2"; package apollo.cyber.proto; enum RunMode { MODE_REALITY = 0; MODE_SIMULATION = 1; } enum ClockMode { MODE_CYBER = 0; MODE_MOCK = 1; } message RunModeConf { optional RunMode run_mode = 1 [default = MODE_REALITY]; optional ClockMode clock_mode = 2 [default = MODE_CYBER]; }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/proto/record.proto
syntax = "proto2"; package apollo.cyber.proto; enum SectionType { SECTION_HEADER = 0; SECTION_CHUNK_HEADER = 1; SECTION_CHUNK_BODY = 2; SECTION_INDEX = 3; SECTION_CHANNEL = 4; }; enum CompressType { COMPRESS_NONE = 0; COMPRESS_BZ2 = 1; COMPRESS_LZ4 = 2; }; message SingleIndex { optional SectionType type = 1; optional uint64 position = 2; oneof cache { ChannelCache channel_cache = 101; ChunkHeaderCache chunk_header_cache = 102; ChunkBodyCache chunk_body_cache = 103; } } message ChunkHeaderCache { optional uint64 message_number = 1; optional uint64 begin_time = 2; optional uint64 end_time = 3; optional uint64 raw_size = 4; } message ChunkBodyCache { optional uint64 message_number = 1; } message ChannelCache { optional uint64 message_number = 1; optional string name = 2; optional string message_type = 3; optional bytes proto_desc = 4; } message SingleMessage { optional string channel_name = 1; optional uint64 time = 2; optional bytes content = 3; } message Header { optional uint32 major_version = 1; optional uint32 minor_version = 2; optional CompressType compress = 3; optional uint64 chunk_interval = 4; optional uint64 segment_interval = 5; optional uint64 index_position = 6 [default = 0]; optional uint64 chunk_number = 7 [default = 0]; optional uint64 channel_number = 8 [default = 0]; optional uint64 begin_time = 9 [default = 0]; optional uint64 end_time = 10 [default = 0]; optional uint64 message_number = 11 [default = 0]; optional uint64 size = 12 [default = 0]; optional bool is_complete = 13 [default = false]; optional uint64 chunk_raw_size = 14; optional uint64 segment_raw_size = 15; } message Channel { optional string name = 1; optional string message_type = 2; optional bytes proto_desc = 3; } message ChunkHeader { optional uint64 begin_time = 1; optional uint64 end_time = 2; optional uint64 message_number = 3; optional uint64 raw_size = 4; } message ChunkBody { repeated SingleMessage messages = 1; } message Index { repeated SingleIndex indexes = 1; }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/proto/qos_profile.proto
syntax = "proto2"; package apollo.cyber.proto; enum QosHistoryPolicy { HISTORY_SYSTEM_DEFAULT = 0; HISTORY_KEEP_LAST = 1; HISTORY_KEEP_ALL = 2; }; enum QosReliabilityPolicy { RELIABILITY_SYSTEM_DEFAULT = 0; RELIABILITY_RELIABLE = 1; RELIABILITY_BEST_EFFORT = 2; }; enum QosDurabilityPolicy { DURABILITY_SYSTEM_DEFAULT = 0; DURABILITY_TRANSIENT_LOCAL = 1; DURABILITY_VOLATILE = 2; }; message QosProfile { optional QosHistoryPolicy history = 1 [default = HISTORY_KEEP_LAST]; optional uint32 depth = 2 [default = 1]; // capacity of history optional uint32 mps = 3 [default = 0]; // messages per second optional QosReliabilityPolicy reliability = 4 [default = RELIABILITY_RELIABLE]; optional QosDurabilityPolicy durability = 5 [default = DURABILITY_VOLATILE]; };
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/proto/choreography_conf.proto
syntax = "proto2"; package apollo.cyber.proto; message ChoreographyTask { optional string name = 1; optional int32 processor = 2; optional uint32 prio = 3 [default = 1]; } message ChoreographyConf { optional uint32 choreography_processor_num = 1; optional string choreography_affinity = 2; optional string choreography_processor_policy = 3; optional int32 choreography_processor_prio = 4; optional string choreography_cpuset = 5; optional uint32 pool_processor_num = 6; optional string pool_affinity = 7; optional string pool_processor_policy = 8; optional int32 pool_processor_prio = 9; optional string pool_cpuset = 10; repeated ChoreographyTask tasks = 11; }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/proto/role_attributes.proto
syntax = "proto2"; package apollo.cyber.proto; import "cyber/proto/qos_profile.proto"; message SocketAddr { optional string ip = 1; // dotted decimal optional uint32 port = 2; }; message RoleAttributes { optional string host_name = 1; optional string host_ip = 2; optional int32 process_id = 3; optional string node_name = 4; optional uint64 node_id = 5; // hash value of node_name // especially for WRITER and READER optional string channel_name = 6; optional uint64 channel_id = 7; // hash value of channel_name optional string message_type = 8; optional bytes proto_desc = 9; optional uint64 id = 10; optional QosProfile qos_profile = 11; optional SocketAddr socket_addr = 12; // reserved for socket communication // especially for SERVER and CLIENT optional string service_name = 13; optional uint64 service_id = 14; // hash value of service_name };
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/proto/transport_conf.proto
syntax = "proto2"; package apollo.cyber.proto; enum OptionalMode { HYBRID = 0; INTRA = 1; SHM = 2; RTPS = 3; } message ShmMulticastLocator { optional string ip = 1; optional uint32 port = 2; }; message ShmConf { optional string notifier_type = 1; optional string shm_type = 2; optional ShmMulticastLocator shm_locator = 3; }; message RtpsParticipantAttr { optional int32 lease_duration = 1 [default = 12]; optional int32 announcement_period = 2 [default = 3]; optional uint32 domain_id_gain = 3 [default = 200]; optional uint32 port_base = 4 [default = 10000]; }; message CommunicationMode { optional OptionalMode same_proc = 1 [default = INTRA]; // INTRA SHM RTPS optional OptionalMode diff_proc = 2 [default = SHM]; // SHM RTPS optional OptionalMode diff_host = 3 [default = RTPS]; // RTPS }; message ResourceLimit { optional uint32 max_history_depth = 1 [default = 1000]; }; message TransportConf { optional ShmConf shm_conf = 1; optional RtpsParticipantAttr participant_attr = 2; optional CommunicationMode communication_mode = 3; optional ResourceLimit resource_limit = 4; };
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/proto/clock.proto
syntax = "proto2"; package apollo.cyber.proto; message Clock { required uint64 clock = 1; }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/proto/classic_conf.proto
syntax = "proto2"; package apollo.cyber.proto; message ClassicTask { optional string name = 1; optional uint32 prio = 2 [default = 1]; optional string group_name = 3; } message SchedGroup { required string name = 1 [default = "default_grp"]; optional uint32 processor_num = 2; optional string affinity = 3; optional string cpuset = 4; optional string processor_policy = 5; optional int32 processor_prio = 6 [default = 0]; repeated ClassicTask tasks = 7; } message ClassicConf { repeated SchedGroup groups = 1; }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/proto/scheduler_conf.proto
syntax = "proto2"; package apollo.cyber.proto; import "cyber/proto/classic_conf.proto"; import "cyber/proto/choreography_conf.proto"; message InnerThread { optional string name = 1; optional string cpuset = 2; optional string policy = 3; optional uint32 prio = 4 [default = 1]; } message SchedulerConf { optional string policy = 1; optional uint32 routine_num = 2; optional uint32 default_proc_num = 3; optional string process_level_cpuset = 4; repeated InnerThread threads = 5; optional ClassicConf classic_conf = 6; optional ChoreographyConf choreography_conf = 7; }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/proto/cyber_conf.proto
syntax = "proto2"; package apollo.cyber.proto; import "cyber/proto/scheduler_conf.proto"; import "cyber/proto/transport_conf.proto"; import "cyber/proto/run_mode_conf.proto"; import "cyber/proto/perf_conf.proto"; message CyberConfig { optional SchedulerConf scheduler_conf = 1; optional TransportConf transport_conf = 2; optional RunModeConf run_mode_conf = 3; optional PerfConf perf_conf = 4; }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/proto/parameter.proto
syntax = "proto2"; package apollo.cyber.proto; enum ParamType { NOT_SET = 0; BOOL = 1; INT = 2; DOUBLE = 3; STRING = 4; PROTOBUF = 5; } message Param { optional string name = 1; optional ParamType type = 2; optional string type_name = 3; oneof oneof_value { bool bool_value = 4; int64 int_value = 5; double double_value = 6; string string_value = 7; } optional bytes proto_desc = 8; } message NodeName { optional string value = 1; } message ParamName { optional string value = 1; } message BoolResult { optional bool value = 1; } message Params { repeated Param param = 1; }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/proto/BUILD
## Auto generated by `proto_build_generator.py` load("@rules_proto//proto:defs.bzl", "proto_library") load("@rules_cc//cc:defs.bzl", "cc_proto_library") load("//tools:python_rules.bzl", "py_proto_library") load("//tools:cc_so_proto_rules.bzl", "cc_so_proto_library") load("//tools/install:install.bzl", "install", "install_files") package(default_visibility = ["//visibility:public"]) filegroup( name = "runtime_files", srcs = ["py_pb2.BUILD"] ) install_files( name = "cyber_proto_hdrs", dest = "cyber/include/proto", files = [ ":topology_change_cc_proto_hdrs", ":dag_conf_cc_proto_hdrs", ":proto_desc_cc_proto_hdrs", ":choreography_conf_cc_proto_hdrs", ":component_conf_cc_proto_hdrs", ":cyber_conf_cc_proto_hdrs", ":perf_conf_cc_proto_hdrs", ":classic_conf_cc_proto_hdrs", ":parameter_cc_proto_hdrs", ":unit_test_cc_proto_hdrs", ":simple_cc_proto_hdrs", ":scheduler_conf_cc_proto_hdrs", ":transport_conf_cc_proto_hdrs", ":qos_profile_cc_proto_hdrs", ":record_cc_proto_hdrs", ":run_mode_conf_cc_proto_hdrs", ":role_attributes_cc_proto_hdrs", ":clock_cc_proto_hdrs", ], ) install( name = "cyber_proto_so", library_dest = "cyber/lib", targets = [ ":libtopology_change_cc_proto.so", ":libdag_conf_cc_proto.so", ":libproto_desc_cc_proto.so", ":libchoreography_conf_cc_proto.so", ":libcomponent_conf_cc_proto.so", ":libcyber_conf_cc_proto.so", ":libperf_conf_cc_proto.so", ":libclassic_conf_cc_proto.so", ":libparameter_cc_proto.so", ":libunit_test_cc_proto.so", ":libsimple_cc_proto.so", ":libscheduler_conf_cc_proto.so", ":libtransport_conf_cc_proto.so", ":libqos_profile_cc_proto.so", ":librecord_cc_proto.so", ":librun_mode_conf_cc_proto.so", ":librole_attributes_cc_proto.so", ":libclock_cc_proto.so", ], ) install_files( name = "pb_cyber", dest = "cyber/python/cyber/proto", files = [ ":record_py_pb2", ":topology_change_py_pb2", ":dag_conf_py_pb2", ":proto_desc_py_pb2", ":choreography_conf_py_pb2", ":component_conf_py_pb2", ":cyber_conf_py_pb2", ":perf_conf_py_pb2", ":classic_conf_py_pb2", ":parameter_py_pb2", ":unit_test_py_pb2", ":simple_py_pb2", ":scheduler_conf_py_pb2", ":transport_conf_py_pb2", ":qos_profile_py_pb2", ":run_mode_conf_py_pb2", ":role_attributes_py_pb2", ":clock_py_pb2", ], ) cc_so_proto_library( name = "topology_change_cc_proto", srcs = [ ":topology_change_proto", ], deps = [ ":role_attributes_cc_proto", ], ) proto_library( name = "topology_change_proto", srcs = ["topology_change.proto"], deps = [ ":role_attributes_proto", ], ) py_proto_library( name = "topology_change_py_pb2", deps = [ ":topology_change_proto", ":role_attributes_py_pb2", ], ) cc_so_proto_library( name = "dag_conf_cc_proto", srcs = [ ":dag_conf_proto", ], deps = [ ":component_conf_cc_proto" ], ) proto_library( name = "dag_conf_proto", srcs = ["dag_conf.proto"], deps = [ ":component_conf_proto", ], ) py_proto_library( name = "dag_conf_py_pb2", deps = [ ":dag_conf_proto", ":component_conf_py_pb2", ], ) cc_so_proto_library( name = "proto_desc_cc_proto", srcs = [ ":proto_desc_proto", ], ) proto_library( name = "proto_desc_proto", srcs = ["proto_desc.proto"], ) py_proto_library( name = "proto_desc_py_pb2", deps = [ ":proto_desc_proto", ], ) cc_so_proto_library( name = "choreography_conf_cc_proto", srcs = [ ":choreography_conf_proto", ], ) proto_library( name = "choreography_conf_proto", srcs = ["choreography_conf.proto"], ) py_proto_library( name = "choreography_conf_py_pb2", deps = [ ":choreography_conf_proto", ], ) cc_so_proto_library( name = "record_cc_proto", srcs = [ ":record_proto", ], ) proto_library( name = "record_proto", srcs = ["record.proto"], ) py_proto_library( name = "record_py_pb2", deps = [ ":record_proto", ], ) cc_so_proto_library( name = "component_conf_cc_proto", srcs = [ ":component_conf_proto", ], deps = [ ":qos_profile_cc_proto" ], ) proto_library( name = "component_conf_proto", srcs = ["component_conf.proto"], deps = [ ":qos_profile_proto", ], ) py_proto_library( name = "component_conf_py_pb2", deps = [ ":component_conf_proto", ":qos_profile_py_pb2", ], ) cc_so_proto_library( name = "cyber_conf_cc_proto", srcs = [ ":cyber_conf_proto", ], deps = [ ":scheduler_conf_cc_proto", ":transport_conf_cc_proto", ":run_mode_conf_cc_proto", ":perf_conf_cc_proto", ], ) proto_library( name = "cyber_conf_proto", srcs = ["cyber_conf.proto"], deps = [ ":scheduler_conf_proto", ":transport_conf_proto", ":run_mode_conf_proto", ":perf_conf_proto", ], ) py_proto_library( name = "cyber_conf_py_pb2", deps = [ ":cyber_conf_proto", ":scheduler_conf_py_pb2", ":transport_conf_py_pb2", ":run_mode_conf_py_pb2", ":perf_conf_py_pb2", ], ) cc_so_proto_library( name = "perf_conf_cc_proto", srcs = [ ":perf_conf_proto", ], ) proto_library( name = "perf_conf_proto", srcs = ["perf_conf.proto"], ) py_proto_library( name = "perf_conf_py_pb2", deps = [ ":perf_conf_proto", ], ) cc_so_proto_library( name = "classic_conf_cc_proto", srcs = [ ":classic_conf_proto", ], ) proto_library( name = "classic_conf_proto", srcs = ["classic_conf.proto"], ) py_proto_library( name = "classic_conf_py_pb2", deps = [ ":classic_conf_proto", ], ) cc_so_proto_library( name = "parameter_cc_proto", srcs = [ ":parameter_proto", ], ) proto_library( name = "parameter_proto", srcs = ["parameter.proto"], ) py_proto_library( name = "parameter_py_pb2", deps = [ ":parameter_proto", ], ) cc_so_proto_library( name = "unit_test_cc_proto", srcs = [ ":unit_test_proto", ], deps = ["//modules/common_msgs/basic_msgs:header_cc_proto"] ) proto_library( name = "unit_test_proto", srcs = ["unit_test.proto"], deps = [ "//modules/common_msgs/basic_msgs:header_proto" ] ) py_proto_library( name = "unit_test_py_pb2", deps = [ ":unit_test_proto", "//modules/common_msgs/basic_msgs:header_py_pb2" ], ) cc_so_proto_library( name = "simple_cc_proto", srcs = [ ":simple_proto", ], deps = ["//modules/common_msgs/basic_msgs:header_cc_proto"] ) proto_library( name = "simple_proto", srcs = ["simple.proto"], deps = [ "//modules/common_msgs/basic_msgs:header_proto" ] ) py_proto_library( name = "simple_py_pb2", deps = [ ":simple_proto", "//modules/common_msgs/basic_msgs:header_py_pb2" ], ) cc_so_proto_library( name = "scheduler_conf_cc_proto", srcs = [ ":scheduler_conf_proto", ], deps = [ ":classic_conf_cc_proto", ":choreography_conf_cc_proto", ], ) proto_library( name = "scheduler_conf_proto", srcs = ["scheduler_conf.proto"], deps = [ ":classic_conf_proto", ":choreography_conf_proto", ], ) py_proto_library( name = "scheduler_conf_py_pb2", deps = [ ":scheduler_conf_proto", ":classic_conf_py_pb2", ":choreography_conf_py_pb2", ], ) cc_so_proto_library( name = "transport_conf_cc_proto", srcs = [ ":transport_conf_proto", ], ) proto_library( name = "transport_conf_proto", srcs = ["transport_conf.proto"], ) py_proto_library( name = "transport_conf_py_pb2", deps = [ ":transport_conf_proto", ], ) cc_so_proto_library( name = "qos_profile_cc_proto", srcs = [ ":qos_profile_proto", ], ) proto_library( name = "qos_profile_proto", srcs = ["qos_profile.proto"], ) py_proto_library( name = "qos_profile_py_pb2", deps = [ ":qos_profile_proto", ], ) cc_so_proto_library( name = "run_mode_conf_cc_proto", srcs = [ ":run_mode_conf_proto", ], ) proto_library( name = "run_mode_conf_proto", srcs = ["run_mode_conf.proto"], ) py_proto_library( name = "run_mode_conf_py_pb2", deps = [ ":run_mode_conf_proto", ], ) cc_so_proto_library( name = "role_attributes_cc_proto", srcs = [ ":role_attributes_proto", ], deps = [ ":qos_profile_cc_proto", ], ) proto_library( name = "role_attributes_proto", srcs = ["role_attributes.proto"], deps = [ ":qos_profile_proto", ], ) py_proto_library( name = "role_attributes_py_pb2", deps = [ ":role_attributes_proto", ":qos_profile_py_pb2", ], ) cc_so_proto_library( name = "clock_cc_proto", srcs = [ ":clock_proto", ], ) proto_library( name = "clock_proto", srcs = ["clock.proto"], ) py_proto_library( name = "clock_py_pb2", deps = [ ":clock_proto", ], )
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/proto/topology_change.proto
syntax = "proto2"; package apollo.cyber.proto; import "cyber/proto/role_attributes.proto"; enum ChangeType { CHANGE_NODE = 1; CHANGE_CHANNEL = 2; CHANGE_SERVICE = 3; CHANGE_PARTICIPANT = 4; }; enum OperateType { OPT_JOIN = 1; OPT_LEAVE = 2; }; enum RoleType { ROLE_NODE = 1; ROLE_WRITER = 2; ROLE_READER = 3; ROLE_SERVER = 4; ROLE_CLIENT = 5; ROLE_PARTICIPANT = 6; }; message ChangeMsg { optional uint64 timestamp = 1; optional ChangeType change_type = 2; optional OperateType operate_type = 3; optional RoleType role_type = 4; optional RoleAttributes role_attr = 5; };
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/proto/dag_conf.proto
syntax = "proto2"; package apollo.cyber.proto; import "cyber/proto/component_conf.proto"; message ComponentInfo { optional string class_name = 1; optional ComponentConfig config = 2; } message TimerComponentInfo { optional string class_name = 1; optional TimerComponentConfig config = 2; } message ModuleConfig { optional string module_library = 1; repeated ComponentInfo components = 2; repeated TimerComponentInfo timer_components = 3; } message DagConfig { repeated ModuleConfig module_config = 1; }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/python/README.md
# Cyber RT Python API : An Example This document is an example demonstrating how to use Cyber RT Python API to write your own Python3 programs. Please make sure you have built Apollo successfully. ## Step 1: Write your own code. Save it as, say, `path/to/my_demo.py`. ```python3 #!/usr/bin/env python3 import sys from cyber.python.cyber_py3 import cyber cyber.init() if not cyber.ok(): print('Well, something went wrong.') sys.exit(1) # Do your job here. cyber.shutdown() ``` ## Step 2: Write Python rule for Bazel to build Edit `path/to/BUILD` file, add the followng section: ``` load("@rules_python//python:defs.bzl", "py_binary") # blablahblah... # Add your own section here py_binary( name = "my_demo", srcs = ["my_demo.py"], deps = [ "//cyber/python/cyber_py3:cyber", ], ) ``` **Note**: Like C++, Python code is also managed by Bazel starting from Apollo 6.0. Please refer to [How to Build and Run Python Apps in Apollo](../../docs/howto/how_to_build_and_run_python_app.md) for more on that. ## Step 3: Build and run the demo program Now you can run the following commands to build and run the demo program. ``` bazel build //path/to:my_demo ./bazel-bin/path/to/my_demo ``` Or simply run ``` bazel run //path/to:my_demo ``` ## More Examples ... Learn more Cyber RT Python examples under the [examples](cyber_py3/examples/) and [tests](cyber_py3/test/) directory.
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/python/BUILD
package( default_visibility = ["//visibility:public"], )
0
apollo_public_repos/apollo/cyber/python
apollo_public_repos/apollo/cyber/python/internal/py_time.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef CYBER_PYTHON_INTERNAL_PY_TIME_H_ #define CYBER_PYTHON_INTERNAL_PY_TIME_H_ #include <unistd.h> #include <memory> #include "cyber/cyber.h" #include "cyber/init.h" #include "cyber/time/rate.h" #include "cyber/time/time.h" namespace apollo { namespace cyber { class PyTime { public: PyTime() = default; explicit PyTime(uint64_t nanoseconds) { time_ = Time(nanoseconds); } static PyTime now() { PyTime t; t.time_ = Time::Now(); return t; } static PyTime mono_time() { PyTime t; t.time_ = Time::MonoTime(); return t; } static void sleep_until(uint64_t nanoseconds) { Time::SleepUntil(Time(nanoseconds)); } double to_sec() const { return time_.ToSecond(); } uint64_t to_nsec() const { return time_.ToNanosecond(); } private: Time time_; }; class PyDuration { public: explicit PyDuration(int64_t nanoseconds) { duration_ = std::make_shared<Duration>(nanoseconds); } void sleep() const { return duration_->Sleep(); } private: std::shared_ptr<Duration> duration_ = nullptr; }; class PyRate { public: explicit PyRate(uint64_t nanoseconds) { rate_ = std::make_shared<Rate>(nanoseconds); } void sleep() const { return rate_->Sleep(); } void reset() const { return rate_->Reset(); } uint64_t get_cycle_time() const { return rate_->CycleTime().ToNanosecond(); } uint64_t get_expected_cycle_time() const { return rate_->ExpectedCycleTime().ToNanosecond(); } private: std::shared_ptr<Rate> rate_ = nullptr; }; } // namespace cyber } // namespace apollo #endif // CYBER_PYTHON_INTERNAL_PY_TIME_H_
0
apollo_public_repos/apollo/cyber/python
apollo_public_repos/apollo/cyber/python/internal/py_timer.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef CYBER_PYTHON_INTERNAL_PY_TIMER_H_ #define CYBER_PYTHON_INTERNAL_PY_TIMER_H_ #include <unistd.h> #include <functional> #include <memory> #include "cyber/cyber.h" #include "cyber/init.h" #include "cyber/timer/timer.h" namespace apollo { namespace cyber { class PyTimer { public: PyTimer() { timer_ = std::make_shared<Timer>(); } PyTimer(uint32_t period, void (*func)(), bool oneshot) { std::function<void()> bound_f = std::bind(func); timer_ = std::make_shared<Timer>(period, bound_f, oneshot); } void start() { timer_->Start(); } void stop() { timer_->Stop(); } void set_option(uint32_t period, void (*func)(), bool oneshot) { std::function<void()> bound_f = std::bind(func); TimerOption time_opt; time_opt.period = period; time_opt.callback = bound_f; time_opt.oneshot = oneshot; timer_->SetTimerOption(time_opt); } private: std::shared_ptr<Timer> timer_ = nullptr; }; } // namespace cyber } // namespace apollo #endif // CYBER_PYTHON_INTERNAL_PY_TIMER_H_
0
apollo_public_repos/apollo/cyber/python
apollo_public_repos/apollo/cyber/python/internal/py_record.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/python/internal/py_record.h" #include <limits> #include <set> #include <string> #include <Python.h> using apollo::cyber::record::PyRecordReader; using apollo::cyber::record::PyRecordWriter; #define PYOBJECT_NULL_STRING PyBytes_FromStringAndSize("", 0) #define C_STR_TO_PY_BYTES(cstr) \ PyBytes_FromStringAndSize(cstr.c_str(), cstr.size()) template <typename T> T PyObjectToPtr(PyObject *pyobj, const std::string &type_ptr) { T obj_ptr = (T)PyCapsule_GetPointer(pyobj, type_ptr.c_str()); if (obj_ptr == nullptr) { AERROR << "PyObjectToPtr failed,type->" << type_ptr << "pyobj: " << pyobj; } return obj_ptr; } PyObject *cyber_new_PyRecordReader(PyObject *self, PyObject *args) { char *filepath = nullptr; Py_ssize_t len = 0; if (!PyArg_ParseTuple(args, const_cast<char *>("s#:new_PyRecordReader"), &filepath, &len)) { AERROR << "cyber_new_PyRecordReader parsetuple failed!"; Py_INCREF(Py_None); return Py_None; } PyRecordReader *reader = new PyRecordReader(std::string(filepath, len)); return PyCapsule_New(reader, "apollo_cyber_record_pyrecordfilereader", nullptr); } PyObject *cyber_delete_PyRecordReader(PyObject *self, PyObject *args) { PyObject *pyobj_rec_reader = nullptr; if (!PyArg_ParseTuple(args, const_cast<char *>("O:delete_PyRecordReader"), &pyobj_rec_reader)) { Py_INCREF(Py_None); return Py_None; } auto *reader = reinterpret_cast<PyRecordReader *>(PyCapsule_GetPointer( pyobj_rec_reader, "apollo_cyber_record_pyrecordfilereader")); if (nullptr == reader) { AERROR << "delete_PyRecordReader:reader ptr is null!"; Py_INCREF(Py_None); return Py_None; } delete reader; Py_INCREF(Py_None); return Py_None; } PyObject *cyber_PyRecordReader_ReadMessage(PyObject *self, PyObject *args) { PyObject *pyobj_reader = nullptr; uint64_t begin_time = 0; uint64_t end_time = std::numeric_limits<uint64_t>::max(); if (!PyArg_ParseTuple(args, const_cast<char *>("OKK:PyRecordReader_ReadMessage"), &pyobj_reader, &begin_time, &end_time)) { return nullptr; } auto *reader = reinterpret_cast<PyRecordReader *>(PyCapsule_GetPointer( pyobj_reader, "apollo_cyber_record_pyrecordfilereader")); if (nullptr == reader) { AERROR << "PyRecordReader_ReadMessage ptr is null!"; return nullptr; } const auto result = reader->ReadMessage(begin_time, end_time); PyObject *pyobj_bag_message = PyDict_New(); PyObject *bld_name = Py_BuildValue("s", result.channel_name.c_str()); PyDict_SetItemString(pyobj_bag_message, "channel_name", bld_name); Py_DECREF(bld_name); PyObject *bld_data = Py_BuildValue("y#", result.data.c_str(), result.data.length()); ACHECK(bld_data) << "Py_BuildValue returns NULL."; PyDict_SetItemString(pyobj_bag_message, "data", bld_data); Py_DECREF(bld_data); PyObject *bld_type = Py_BuildValue("s", result.data_type.c_str()); PyDict_SetItemString(pyobj_bag_message, "data_type", bld_type); Py_DECREF(bld_type); PyObject *bld_time = Py_BuildValue("s", "timestamp"); PyObject *bld_rtime = Py_BuildValue("K", result.timestamp); PyDict_SetItem(pyobj_bag_message, bld_time, bld_rtime); Py_DECREF(bld_time); Py_DECREF(bld_rtime); PyObject *bld_end = Py_BuildValue("s", "end"); PyDict_SetItem(pyobj_bag_message, bld_end, result.end ? Py_True : Py_False); Py_DECREF(bld_end); return pyobj_bag_message; } PyObject *cyber_PyRecordReader_GetMessageNumber(PyObject *self, PyObject *args) { PyObject *pyobj_reader = nullptr; char *channel_name = nullptr; if (!PyArg_ParseTuple( args, const_cast<char *>("Os:PyRecordReader_GetMessageNumber"), &pyobj_reader, &channel_name)) { AERROR << "PyRecordReader_GetMessageNumber:PyRecordReader failed!"; return PyLong_FromUnsignedLongLong(0); } auto *reader = reinterpret_cast<PyRecordReader *>(PyCapsule_GetPointer( pyobj_reader, "apollo_cyber_record_pyrecordfilereader")); if (nullptr == reader) { AERROR << "PyRecordReader_GetMessageNumber ptr is null!"; return PyLong_FromUnsignedLongLong(0); } uint64_t num = reader->GetMessageNumber(channel_name); return PyLong_FromUnsignedLongLong(num); } PyObject *cyber_PyRecordReader_GetMessageType(PyObject *self, PyObject *args) { PyObject *pyobj_reader = nullptr; char *channel_name = nullptr; if (!PyArg_ParseTuple( args, const_cast<char *>("Os:cyber_PyRecordReader_GetMessageType"), &pyobj_reader, &channel_name)) { AERROR << "PyRecordReader_GetMessageType:PyRecordReader failed!"; return PYOBJECT_NULL_STRING; } auto *reader = reinterpret_cast<PyRecordReader *>(PyCapsule_GetPointer( pyobj_reader, "apollo_cyber_record_pyrecordfilereader")); if (nullptr == reader) { AERROR << "PyRecordReader_GetMessageType ptr is null!"; return PYOBJECT_NULL_STRING; } const std::string msg_type = reader->GetMessageType(channel_name); return C_STR_TO_PY_BYTES(msg_type); } PyObject *cyber_PyRecordReader_GetProtoDesc(PyObject *self, PyObject *args) { PyObject *pyobj_reader = nullptr; char *channel_name = nullptr; if (!PyArg_ParseTuple(args, const_cast<char *>("Os:PyRecordReader_GetProtoDesc"), &pyobj_reader, &channel_name)) { AERROR << "PyRecordReader_GetProtoDesc failed!"; return PYOBJECT_NULL_STRING; } auto *reader = reinterpret_cast<PyRecordReader *>(PyCapsule_GetPointer( pyobj_reader, "apollo_cyber_record_pyrecordfilereader")); if (nullptr == reader) { AERROR << "PyRecordReader_GetProtoDesc ptr is null!"; return PYOBJECT_NULL_STRING; } const std::string pb_desc = reader->GetProtoDesc(channel_name); return C_STR_TO_PY_BYTES(pb_desc); } PyObject *cyber_PyRecordReader_GetHeaderString(PyObject *self, PyObject *args) { PyObject *pyobj_reader = nullptr; if (!PyArg_ParseTuple( args, const_cast<char *>("O:cyber_PyRecordReader_GetHeaderString"), &pyobj_reader)) { return PYOBJECT_NULL_STRING; } auto *reader = reinterpret_cast<PyRecordReader *>(PyCapsule_GetPointer( pyobj_reader, "apollo_cyber_record_pyrecordfilereader")); if (nullptr == reader) { AERROR << "PyRecordReader_GetHeaderString ptr is null!"; return PYOBJECT_NULL_STRING; } const std::string header_string = reader->GetHeaderString(); return C_STR_TO_PY_BYTES(header_string); } PyObject *cyber_PyRecordReader_Reset(PyObject *self, PyObject *args) { PyObject *pyobj_reader = nullptr; if (!PyArg_ParseTuple(args, const_cast<char *>("O:cyber_PyRecordReader_Reset"), &pyobj_reader)) { AERROR << "cyber_PyRecordReader_Reset:PyArg_ParseTuple failed!"; Py_INCREF(Py_None); return Py_None; } auto *reader = reinterpret_cast<PyRecordReader *>(PyCapsule_GetPointer( pyobj_reader, "apollo_cyber_record_pyrecordfilereader")); if (nullptr == reader) { AERROR << "PyRecordReader_Reset reader is null!"; Py_INCREF(Py_None); return Py_None; } reader->Reset(); Py_INCREF(Py_None); return Py_None; } PyObject *cyber_PyRecordReader_GetChannelList(PyObject *self, PyObject *args) { PyObject *pyobj_reader = nullptr; if (!PyArg_ParseTuple( args, const_cast<char *>("O:cyber_PyRecordReader_GetChannelList"), &pyobj_reader)) { AERROR << "cyber_PyRecordReader_GetChannelList:PyArg_ParseTuple failed!"; Py_INCREF(Py_None); return Py_None; } auto *reader = reinterpret_cast<PyRecordReader *>(PyCapsule_GetPointer( pyobj_reader, "apollo_cyber_record_pyrecordfilereader")); if (nullptr == reader) { AERROR << "PyRecordReader_GetChannelList reader is null!"; Py_INCREF(Py_None); return Py_None; } std::set<std::string> channel_list = reader->GetChannelList(); PyObject *pyobj_list = PyList_New(channel_list.size()); size_t pos = 0; for (const std::string &channel : channel_list) { PyList_SetItem(pyobj_list, pos, Py_BuildValue("s", channel.c_str())); pos++; } return pyobj_list; } PyObject *cyber_new_PyRecordWriter(PyObject *self, PyObject *args) { PyRecordWriter *writer = new PyRecordWriter(); return PyCapsule_New(writer, "apollo_cyber_record_pyrecordfilewriter", nullptr); } PyObject *cyber_delete_PyRecordWriter(PyObject *self, PyObject *args) { PyObject *pyobj_rec_writer = nullptr; if (!PyArg_ParseTuple(args, const_cast<char *>("O:delete_PyRecordWriter"), &pyobj_rec_writer)) { Py_INCREF(Py_None); return Py_None; } auto *writer = reinterpret_cast<PyRecordWriter *>(PyCapsule_GetPointer( pyobj_rec_writer, "apollo_cyber_record_pyrecordfilewriter")); if (nullptr == writer) { AERROR << "delete_PyRecordWriter:writer is null!"; Py_INCREF(Py_None); return Py_None; } delete writer; Py_INCREF(Py_None); return Py_None; } PyObject *cyber_PyRecordWriter_Open(PyObject *self, PyObject *args) { PyObject *pyobj_rec_writer = nullptr; char *path = nullptr; Py_ssize_t len = 0; if (!PyArg_ParseTuple(args, const_cast<char *>("Os#:cyber_PyRecordWriter_Open"), &pyobj_rec_writer, &path, &len)) { AERROR << "cyber_PyRecordWriter_Open:PyArg_ParseTuple failed!"; Py_RETURN_FALSE; } PyRecordWriter *writer = PyObjectToPtr<PyRecordWriter *>( pyobj_rec_writer, "apollo_cyber_record_pyrecordfilewriter"); if (nullptr == writer) { AERROR << "PyRecordWriter_Open:writer is null!"; Py_RETURN_FALSE; } std::string path_str(path, len); if (!writer->Open(path_str)) { Py_RETURN_FALSE; } Py_RETURN_TRUE; } PyObject *cyber_PyRecordWriter_Close(PyObject *self, PyObject *args) { PyObject *pyobj_rec_writer = nullptr; if (!PyArg_ParseTuple(args, const_cast<char *>("O:delete_PyRecordWriter"), &pyobj_rec_writer)) { Py_INCREF(Py_None); return Py_None; } auto *writer = reinterpret_cast<PyRecordWriter *>(PyCapsule_GetPointer( pyobj_rec_writer, "apollo_cyber_record_pyrecordfilewriter")); if (nullptr == writer) { AERROR << "cyber_PyRecordWriter_Close: writer is null!"; Py_INCREF(Py_None); return Py_None; } writer->Close(); Py_INCREF(Py_None); return Py_None; } PyObject *cyber_PyRecordWriter_WriteChannel(PyObject *self, PyObject *args) { PyObject *pyobj_rec_writer = nullptr; char *channel = nullptr; char *type = nullptr; char *proto_desc = nullptr; Py_ssize_t len = 0; if (!PyArg_ParseTuple( args, const_cast<char *>("Osss#:cyber_PyRecordWriter_WriteChannel"), &pyobj_rec_writer, &channel, &type, &proto_desc, &len)) { AERROR << "cyber_PyRecordWriter_WriteChannel parsetuple failed!"; Py_RETURN_FALSE; } auto *writer = PyObjectToPtr<PyRecordWriter *>( pyobj_rec_writer, "apollo_cyber_record_pyrecordfilewriter"); if (nullptr == writer) { AERROR << "cyber_PyRecordWriter_WriteChannel:writer ptr is null!"; Py_RETURN_FALSE; } std::string proto_desc_str(proto_desc, len); if (!writer->WriteChannel(channel, type, proto_desc_str)) { Py_RETURN_FALSE; } Py_RETURN_TRUE; } PyObject *cyber_PyRecordWriter_WriteMessage(PyObject *self, PyObject *args) { PyObject *pyobj_rec_writer = nullptr; char *channel_name = nullptr; char *rawmessage = nullptr; Py_ssize_t len = 0; uint64_t time = 0; char *proto_desc = nullptr; Py_ssize_t len_desc = 0; if (!PyArg_ParseTuple( args, const_cast<char *>("Oss#Ks#:cyber_PyRecordWriter_WriteMessage"), &pyobj_rec_writer, &channel_name, &rawmessage, &len, &time, &proto_desc, &len_desc)) { AERROR << "cyber_PyRecordWriter_WriteMessage parsetuple failed!"; Py_RETURN_FALSE; } auto *writer = PyObjectToPtr<PyRecordWriter *>( pyobj_rec_writer, "apollo_cyber_record_pyrecordfilewriter"); if (nullptr == writer) { AERROR << "cyber_PyRecordWriter_WriteMessage:writer ptr is null!"; Py_RETURN_FALSE; } std::string rawmessage_str(rawmessage, len); std::string desc_str(proto_desc, len_desc); if (!writer->WriteMessage(channel_name, rawmessage_str, time, desc_str)) { AERROR << "cyber_PyRecordWriter_WriteMessage:WriteMessage failed!"; Py_RETURN_FALSE; } Py_RETURN_TRUE; } PyObject *cyber_PyRecordWriter_SetSizeOfFileSegmentation(PyObject *self, PyObject *args) { PyObject *pyobj_rec_writer = nullptr; uint64_t size_kilobytes = 0; if (!PyArg_ParseTuple( args, const_cast<char *>( "OK:cyber_PyRecordWriter_SetSizeOfFileSegmentation"), &pyobj_rec_writer, &size_kilobytes)) { AERROR << "cyber_PyRecordWriter_SetSizeOfFileSegmentation parsetuple failed!"; Py_RETURN_FALSE; } auto *writer = PyObjectToPtr<PyRecordWriter *>( pyobj_rec_writer, "apollo_cyber_record_pyrecordfilewriter"); if (nullptr == writer) { AERROR << "cyber_PyRecordWriter_SetSizeOfFileSegmentation:writer ptr is null!"; Py_RETURN_FALSE; } if (!writer->SetSizeOfFileSegmentation(size_kilobytes)) { AERROR << "cyber_PyRecordWriter_SetSizeOfFileSegmentation failed!"; Py_RETURN_FALSE; } Py_RETURN_TRUE; } PyObject *cyber_PyRecordWriter_SetIntervalOfFileSegmentation(PyObject *self, PyObject *args) { PyObject *pyobj_rec_writer = nullptr; uint64_t time_sec = 0; if (!PyArg_ParseTuple( args, const_cast<char *>( "OK:cyber_PyRecordWriter_SetIntervalOfFileSegmentation"), &pyobj_rec_writer, &time_sec)) { AERROR << "cyber_PyRecordWriter_SetIntervalOfFileSegmentation parsetuple " "failed!"; Py_RETURN_FALSE; } auto *writer = PyObjectToPtr<PyRecordWriter *>( pyobj_rec_writer, "apollo_cyber_record_pyrecordfilewriter"); if (nullptr == writer) { AERROR << "cyber_PyRecordWriter_SetIntervalOfFileSegmentation:writer ptr " "is null!"; Py_RETURN_FALSE; } if (!writer->SetIntervalOfFileSegmentation(time_sec)) { AERROR << "cyber_PyRecordWriter_SetIntervalOfFileSegmentation failed!"; Py_RETURN_FALSE; } Py_RETURN_TRUE; } PyObject *cyber_PyRecordWriter_GetMessageNumber(PyObject *self, PyObject *args) { PyObject *pyobj_rec_writer = nullptr; char *channel_name = nullptr; if (!PyArg_ParseTuple( args, const_cast<char *>("Os:PyRecordWriter_GetMessageNumber"), &pyobj_rec_writer, &channel_name)) { AERROR << "PyRecordWriter_GetMessageNumber:PyRecordWriter_GetMessageNumber " "failed!"; return PyLong_FromUnsignedLongLong(0); } auto *writer = reinterpret_cast<PyRecordWriter *>(PyCapsule_GetPointer( pyobj_rec_writer, "apollo_cyber_record_pyrecordfilewriter")); if (nullptr == writer) { AERROR << "PyRecordWriter_GetMessageNumber ptr is null!"; return PyLong_FromUnsignedLongLong(0); } uint64_t num = writer->GetMessageNumber(channel_name); return PyLong_FromUnsignedLongLong(num); } PyObject *cyber_PyRecordWriter_GetMessageType(PyObject *self, PyObject *args) { PyObject *pyobj_rec_writer = nullptr; char *channel_name = nullptr; if (!PyArg_ParseTuple(args, const_cast<char *>("Os:PyRecordWriter_GetMessageType"), &pyobj_rec_writer, &channel_name)) { AERROR << "PyRecordWriter_GetMessageType failed!"; return PYOBJECT_NULL_STRING; } auto *writer = reinterpret_cast<PyRecordWriter *>(PyCapsule_GetPointer( pyobj_rec_writer, "apollo_cyber_record_pyrecordfilewriter")); if (nullptr == writer) { AERROR << "PyRecordWriter_GetMessageType ptr is null!"; return PYOBJECT_NULL_STRING; } std::string msg_type = writer->GetMessageType(channel_name); return C_STR_TO_PY_BYTES(msg_type); } PyObject *cyber_PyRecordWriter_GetProtoDesc(PyObject *self, PyObject *args) { PyObject *pyobj_rec_writer = nullptr; char *channel_name = nullptr; if (!PyArg_ParseTuple(args, const_cast<char *>("Os:PyRecordWriter_GetProtoDesc"), &pyobj_rec_writer, &channel_name)) { AERROR << "PyRecordWriter_GetProtoDesc failed!"; return PYOBJECT_NULL_STRING; } auto *writer = reinterpret_cast<PyRecordWriter *>(PyCapsule_GetPointer( pyobj_rec_writer, "apollo_cyber_record_pyrecordfilewriter")); if (nullptr == writer) { AERROR << "PyRecordWriter_GetProtoDesc ptr is null!"; return PYOBJECT_NULL_STRING; } const std::string proto_desc_str = writer->GetProtoDesc(channel_name); return C_STR_TO_PY_BYTES(proto_desc_str); } static PyMethodDef _cyber_record_methods[] = { // PyRecordReader fun {"new_PyRecordReader", cyber_new_PyRecordReader, METH_VARARGS, ""}, {"delete_PyRecordReader", cyber_delete_PyRecordReader, METH_VARARGS, ""}, {"PyRecordReader_ReadMessage", cyber_PyRecordReader_ReadMessage, METH_VARARGS, ""}, {"PyRecordReader_GetMessageNumber", cyber_PyRecordReader_GetMessageNumber, METH_VARARGS, ""}, {"PyRecordReader_GetMessageType", cyber_PyRecordReader_GetMessageType, METH_VARARGS, ""}, {"PyRecordReader_GetProtoDesc", cyber_PyRecordReader_GetProtoDesc, METH_VARARGS, ""}, {"PyRecordReader_GetHeaderString", cyber_PyRecordReader_GetHeaderString, METH_VARARGS, ""}, {"PyRecordReader_Reset", cyber_PyRecordReader_Reset, METH_VARARGS, ""}, {"PyRecordReader_GetChannelList", cyber_PyRecordReader_GetChannelList, METH_VARARGS, ""}, // PyRecordWriter fun {"new_PyRecordWriter", cyber_new_PyRecordWriter, METH_VARARGS, ""}, {"delete_PyRecordWriter", cyber_delete_PyRecordWriter, METH_VARARGS, ""}, {"PyRecordWriter_Open", cyber_PyRecordWriter_Open, METH_VARARGS, ""}, {"PyRecordWriter_Close", cyber_PyRecordWriter_Close, METH_VARARGS, ""}, {"PyRecordWriter_WriteChannel", cyber_PyRecordWriter_WriteChannel, METH_VARARGS, ""}, {"PyRecordWriter_WriteMessage", cyber_PyRecordWriter_WriteMessage, METH_VARARGS, ""}, {"PyRecordWriter_SetSizeOfFileSegmentation", cyber_PyRecordWriter_SetSizeOfFileSegmentation, METH_VARARGS, ""}, {"PyRecordWriter_SetIntervalOfFileSegmentation", cyber_PyRecordWriter_SetIntervalOfFileSegmentation, METH_VARARGS, ""}, {"PyRecordWriter_GetMessageNumber", cyber_PyRecordWriter_GetMessageNumber, METH_VARARGS, ""}, {"PyRecordWriter_GetMessageType", cyber_PyRecordWriter_GetMessageType, METH_VARARGS, ""}, {"PyRecordWriter_GetProtoDesc", cyber_PyRecordWriter_GetProtoDesc, METH_VARARGS, ""}, {nullptr, nullptr, 0, nullptr} /* sentinel */ }; /// Init function of this module PyMODINIT_FUNC PyInit__cyber_record_wrapper(void) { static struct PyModuleDef module_def = { PyModuleDef_HEAD_INIT, "_cyber_record_wrapper", // Module name. "CyberRecord module", // Module doc. -1, // Module size. _cyber_record_methods, // Module methods. nullptr, nullptr, nullptr, nullptr, }; AINFO << "init _cyber_record_wrapper"; return PyModule_Create(&module_def); }
0
apollo_public_repos/apollo/cyber/python
apollo_public_repos/apollo/cyber/python/internal/py_timer.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/python/internal/py_timer.h" #include <set> #include <string> #include <Python.h> using apollo::cyber::PyTimer; #define PyInt_AsLong PyLong_AsLong template <typename T> T PyObjectToPtr(PyObject* pyobj, const std::string& type_ptr) { T obj_ptr = (T)PyCapsule_GetPointer(pyobj, type_ptr.c_str()); if (obj_ptr == nullptr) { AERROR << "PyObjectToPtr failed,type->" << type_ptr << "pyobj: " << pyobj; } return obj_ptr; } PyObject* cyber_new_PyTimer(PyObject* self, PyObject* args) { uint32_t period = 0; PyObject* pyobj_regist_fun = nullptr; unsigned int oneshot = 0; if (!PyArg_ParseTuple(args, const_cast<char*>("kOI:cyber_new_PyTimer"), &period, &pyobj_regist_fun, &oneshot)) { AERROR << "cyber_new_PyTimer parsetuple failed!"; Py_INCREF(Py_None); return Py_None; } void (*callback_fun)() = (void (*)())0; callback_fun = (void (*)())PyInt_AsLong(pyobj_regist_fun); PyTimer* pytimer = new PyTimer(period, callback_fun, oneshot != 0); return PyCapsule_New(pytimer, "apollo_cybertron_pytimer", nullptr); } PyObject* cyber_new_PyTimer_noparam(PyObject* self, PyObject* args) { PyTimer* pytimer = new PyTimer(); return PyCapsule_New(pytimer, "apollo_cybertron_pytimer", nullptr); } PyObject* cyber_delete_PyTimer(PyObject* self, PyObject* args) { PyObject* pyobj_timer = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("O:cyber_delete_PyTimer"), &pyobj_timer)) { Py_INCREF(Py_None); return Py_None; } auto* pytimer = reinterpret_cast<PyTimer*>( PyCapsule_GetPointer(pyobj_timer, "apollo_cybertron_pytimer")); if (nullptr == pytimer) { AERROR << "cyber_delete_PyTimer:timer ptr is null!"; Py_INCREF(Py_None); return Py_None; } delete pytimer; Py_INCREF(Py_None); return Py_None; } PyObject* cyber_PyTimer_start(PyObject* self, PyObject* args) { PyObject* pyobj_timer = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("O:cyber_delete_PyTimer"), &pyobj_timer)) { Py_INCREF(Py_None); return Py_None; } auto* pytimer = reinterpret_cast<PyTimer*>( PyCapsule_GetPointer(pyobj_timer, "apollo_cybertron_pytimer")); if (nullptr == pytimer) { AERROR << "cyber_delete_PyTimer:timer ptr is null!"; Py_INCREF(Py_None); return Py_None; } pytimer->start(); Py_INCREF(Py_None); return Py_None; } PyObject* cyber_PyTimer_stop(PyObject* self, PyObject* args) { PyObject* pyobj_timer = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("O:cyber_delete_PyTimer"), &pyobj_timer)) { Py_INCREF(Py_None); return Py_None; } auto* pytimer = reinterpret_cast<PyTimer*>( PyCapsule_GetPointer(pyobj_timer, "apollo_cybertron_pytimer")); if (nullptr == pytimer) { AERROR << "cyber_delete_PyTimer:timer ptr is null!"; Py_INCREF(Py_None); return Py_None; } pytimer->stop(); Py_INCREF(Py_None); return Py_None; } PyObject* cyber_PyTimer_set_option(PyObject* self, PyObject* args) { PyObject* pyobj_timer = nullptr; uint32_t period = 0; PyObject* pyobj_regist_fun = nullptr; unsigned int oneshot = 0; void (*callback_fun)() = (void (*)())0; if (!PyArg_ParseTuple(args, const_cast<char*>("OkOI:cyber_PyTimer_set_option"), &pyobj_timer, &period, &pyobj_regist_fun, &oneshot)) { Py_INCREF(Py_None); return Py_None; } PyTimer* pytimer = PyObjectToPtr<PyTimer*>(pyobj_timer, "apollo_cybertron_pytimer"); callback_fun = (void (*)())PyInt_AsLong(pyobj_regist_fun); if (nullptr == pytimer) { AERROR << "cyber_PyTimer_set_option ptr is null!"; Py_INCREF(Py_None); return Py_None; } pytimer->set_option(period, callback_fun, oneshot != 0); Py_INCREF(Py_None); return Py_None; } static PyMethodDef _cyber_timer_methods[] = { {"new_PyTimer_noparam", cyber_new_PyTimer_noparam, METH_NOARGS, ""}, {"new_PyTimer", cyber_new_PyTimer, METH_VARARGS, ""}, {"delete_PyTimer", cyber_delete_PyTimer, METH_VARARGS, ""}, {"PyTimer_start", cyber_PyTimer_start, METH_VARARGS, ""}, {"PyTimer_stop", cyber_PyTimer_stop, METH_VARARGS, ""}, {"PyTimer_set_option", cyber_PyTimer_set_option, METH_VARARGS, ""}, {nullptr, nullptr, 0, nullptr} /* sentinel */ }; /// Init function of this module PyMODINIT_FUNC PyInit__cyber_timer_wrapper(void) { static struct PyModuleDef module_def = { PyModuleDef_HEAD_INIT, "_cyber_timer_wrapper", // Module name. "CyberTimer module", // Module doc. -1, // Module size. _cyber_timer_methods, // Module methods. nullptr, nullptr, nullptr, nullptr, }; return PyModule_Create(&module_def); }
0
apollo_public_repos/apollo/cyber/python
apollo_public_repos/apollo/cyber/python/internal/py_time.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/python/internal/py_time.h" #include <set> #include <string> #include <Python.h> using apollo::cyber::PyDuration; using apollo::cyber::PyRate; using apollo::cyber::PyTime; #define PYOBJECT_NULL_STRING PyString_FromStringAndSize("", 0) template <typename T> T PyObjectToPtr(PyObject* pyobj, const std::string& type_ptr) { T obj_ptr = (T)PyCapsule_GetPointer(pyobj, type_ptr.c_str()); if (obj_ptr == nullptr) { AERROR << "PyObjectToPtr failed,type->" << type_ptr << "pyobj: " << pyobj; } return obj_ptr; } PyObject* cyber_new_PyTime(PyObject* self, PyObject* args) { uint64_t nanoseconds = 0; if (!PyArg_ParseTuple(args, const_cast<char*>("K:cyber_new_PyTime"), &nanoseconds)) { AERROR << "cyber_new_PyTime parsetuple failed!"; Py_INCREF(Py_None); return Py_None; } PyTime* pytime = new PyTime(nanoseconds); return PyCapsule_New(pytime, "apollo_cybertron_pytime", nullptr); } PyObject* cyber_delete_PyTime(PyObject* self, PyObject* args) { PyObject* pyobj_time = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("O:cyber_delete_PyTime"), &pyobj_time)) { Py_INCREF(Py_None); return Py_None; } auto* pytime = reinterpret_cast<PyTime*>( PyCapsule_GetPointer(pyobj_time, "apollo_cybertron_pytime")); if (nullptr == pytime) { AERROR << "cyber_delete_PyTime:time ptr is null!"; Py_INCREF(Py_None); return Py_None; } delete pytime; Py_INCREF(Py_None); return Py_None; } PyObject* cyber_PyTime_to_sec(PyObject* self, PyObject* args) { PyObject* pyobj_time = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("O:cyber_PyTime_to_sec"), &pyobj_time)) { AERROR << "cyber_PyTime_to_sec:PyArg_ParseTuple failed!"; return PyFloat_FromDouble(0); } auto* pytime = reinterpret_cast<PyTime*>( PyCapsule_GetPointer(pyobj_time, "apollo_cybertron_pytime")); if (nullptr == pytime) { AERROR << "cyber_PyTime_to_sec ptr is null!"; return PyFloat_FromDouble(0); } double num = pytime->to_sec(); return PyFloat_FromDouble(num); } PyObject* cyber_PyTime_to_nsec(PyObject* self, PyObject* args) { PyObject* pyobj_time = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("O:cyber_PyTime_to_nsec"), &pyobj_time)) { AERROR << "cyber_PyTime_to_nsec:PyArg_ParseTuple failed!"; return PyLong_FromUnsignedLongLong(0); } auto* pytime = reinterpret_cast<PyTime*>( PyCapsule_GetPointer(pyobj_time, "apollo_cybertron_pytime")); if (nullptr == pytime) { AERROR << "cyber_PyTime_to_nsec ptr is null!"; return PyLong_FromUnsignedLongLong(0); } uint64_t num = pytime->to_nsec(); return PyLong_FromUnsignedLongLong(num); } PyObject* cyber_PyTime_sleep_until(PyObject* self, PyObject* args) { PyObject* pyobj_time = nullptr; uint64_t nanoseconds = 0; if (!PyArg_ParseTuple(args, const_cast<char*>("OK:cyber_PyTime_sleep_until"), &pyobj_time, &nanoseconds)) { AERROR << "cyber_PyTime_sleep_until:PyArg_ParseTuple failed!"; Py_INCREF(Py_None); return Py_None; } auto* pytime = reinterpret_cast<PyTime*>( PyCapsule_GetPointer(pyobj_time, "apollo_cybertron_pytime")); if (nullptr == pytime) { AERROR << "cyber_PyTime_sleep_until ptr is null!"; Py_INCREF(Py_None); return Py_None; } pytime->sleep_until(nanoseconds); Py_INCREF(Py_None); return Py_None; } PyObject* cyber_PyTime_now(PyObject* self, PyObject* args) { PyTime now = PyTime::now(); return PyLong_FromUnsignedLongLong(now.to_nsec()); } PyObject* cyber_PyTime_mono_time(PyObject* self, PyObject* args) { PyTime mono_time = PyTime::mono_time(); return PyLong_FromUnsignedLongLong(mono_time.to_nsec()); } // duration PyObject* cyber_new_PyDuration(PyObject* self, PyObject* args) { uint64_t nanoseconds = 0; if (!PyArg_ParseTuple(args, const_cast<char*>("L:cyber_new_PyDuration"), &nanoseconds)) { AERROR << "cyber_new_PyDuration parsetuple failed!"; Py_INCREF(Py_None); return Py_None; } PyDuration* pyduration = new PyDuration(nanoseconds); return PyCapsule_New(pyduration, "apollo_cybertron_pyduration", nullptr); } PyObject* cyber_delete_PyDuration(PyObject* self, PyObject* args) { PyObject* pyobj_duration = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("O:cyber_delete_PyDuration"), &pyobj_duration)) { Py_INCREF(Py_None); return Py_None; } auto* pyduration = reinterpret_cast<PyDuration*>( PyCapsule_GetPointer(pyobj_duration, "apollo_cybertron_pyduration")); if (nullptr == pyduration) { AERROR << "cyber_delete_PyDuration:pyduration ptr is null!"; Py_INCREF(Py_None); return Py_None; } delete pyduration; Py_INCREF(Py_None); return Py_None; } PyObject* cyber_PyDuration_sleep(PyObject* self, PyObject* args) { PyObject* pyobj_duration = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("O:cyber_PyDuration_sleep"), &pyobj_duration)) { Py_INCREF(Py_None); return Py_None; } auto* pyduration = reinterpret_cast<PyDuration*>( PyCapsule_GetPointer(pyobj_duration, "apollo_cybertron_pyduration")); if (nullptr == pyduration) { AERROR << "cyber_PyDuration_sleep:pyduration ptr is null!"; Py_INCREF(Py_None); return Py_None; } pyduration->sleep(); Py_INCREF(Py_None); return Py_None; } // rate PyObject* cyber_new_PyRate(PyObject* self, PyObject* args) { uint64_t nanoseconds = 0; if (!PyArg_ParseTuple(args, const_cast<char*>("L:cyber_new_PyRate"), &nanoseconds)) { AERROR << "cyber_new_PyRate parsetuple failed!"; Py_INCREF(Py_None); return Py_None; } PyRate* pyrate = new PyRate(nanoseconds); return PyCapsule_New(pyrate, "apollo_cybertron_pyrate", nullptr); } PyObject* cyber_delete_PyRate(PyObject* self, PyObject* args) { PyObject* pyobj_rate = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("O:cyber_delete_PyRate"), &pyobj_rate)) { Py_INCREF(Py_None); return Py_None; } auto* pyrate = reinterpret_cast<PyRate*>( PyCapsule_GetPointer(pyobj_rate, "apollo_cybertron_pyrate")); if (nullptr == pyrate) { AERROR << "cyber_delete_PyRate:rate ptr is null!"; Py_INCREF(Py_None); return Py_None; } delete pyrate; Py_INCREF(Py_None); return Py_None; } PyObject* cyber_PyRate_sleep(PyObject* self, PyObject* args) { PyObject* pyobj_rate = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("O:cyber_PyRate_sleep"), &pyobj_rate)) { Py_INCREF(Py_None); return Py_None; } auto* pyrate = reinterpret_cast<PyRate*>( PyCapsule_GetPointer(pyobj_rate, "apollo_cybertron_pyrate")); if (nullptr == pyrate) { AERROR << "cyber_PyRate_sleep:rate ptr is null!"; Py_INCREF(Py_None); return Py_None; } pyrate->sleep(); Py_INCREF(Py_None); return Py_None; } PyObject* cyber_PyRate_reset(PyObject* self, PyObject* args) { PyObject* pyobj_rate = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("O:cyber_PyRate_reset"), &pyobj_rate)) { Py_INCREF(Py_None); return Py_None; } auto* pyrate = reinterpret_cast<PyRate*>( PyCapsule_GetPointer(pyobj_rate, "apollo_cybertron_pyrate")); if (nullptr == pyrate) { AERROR << "cyber_PyRate_reset:rate ptr is null!"; Py_INCREF(Py_None); return Py_None; } pyrate->reset(); Py_INCREF(Py_None); return Py_None; } PyObject* cyber_PyRate_get_cycle_time(PyObject* self, PyObject* args) { PyObject* pyobj_rate = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("O:cyber_PyRate_get_cycle_time"), &pyobj_rate)) { return PyLong_FromUnsignedLongLong(0); } auto* pyrate = reinterpret_cast<PyRate*>( PyCapsule_GetPointer(pyobj_rate, "apollo_cybertron_pyrate")); if (nullptr == pyrate) { AERROR << "cyber_PyRate_get_cycle_time:rate ptr is null!"; return PyLong_FromUnsignedLongLong(0); } uint64_t ctime = pyrate->get_cycle_time(); return PyLong_FromUnsignedLongLong(ctime); } PyObject* cyber_PyRate_get_expected_cycle_time(PyObject* self, PyObject* args) { PyObject* pyobj_rate = nullptr; if (!PyArg_ParseTuple( args, const_cast<char*>("O:cyber_PyRate_get_expected_cycle_time"), &pyobj_rate)) { return PyLong_FromUnsignedLongLong(0); } auto* pyrate = reinterpret_cast<PyRate*>( PyCapsule_GetPointer(pyobj_rate, "apollo_cybertron_pyrate")); if (nullptr == pyrate) { AERROR << "cyber_PyRate_get_expected_cycle_time:rate ptr is null!"; return PyLong_FromUnsignedLongLong(0); } uint64_t exp_cycle_time = pyrate->get_expected_cycle_time(); return PyLong_FromUnsignedLongLong(exp_cycle_time); } static PyMethodDef _cyber_time_methods[] = { // PyTime fun {"new_PyTime", cyber_new_PyTime, METH_VARARGS, ""}, {"delete_PyTime", cyber_delete_PyTime, METH_VARARGS, ""}, {"PyTime_now", cyber_PyTime_now, METH_VARARGS, ""}, {"PyTime_mono_time", cyber_PyTime_mono_time, METH_VARARGS, ""}, {"PyTime_to_sec", cyber_PyTime_to_sec, METH_VARARGS, ""}, {"PyTime_to_nsec", cyber_PyTime_to_nsec, METH_VARARGS, ""}, {"PyTime_sleep_until", cyber_PyTime_sleep_until, METH_VARARGS, ""}, // PyDuration {"new_PyDuration", cyber_new_PyDuration, METH_VARARGS, ""}, {"delete_PyDuration", cyber_delete_PyDuration, METH_VARARGS, ""}, {"PyDuration_sleep", cyber_PyDuration_sleep, METH_VARARGS, ""}, // PyRate {"new_PyRate", cyber_new_PyRate, METH_VARARGS, ""}, {"delete_PyRate", cyber_delete_PyRate, METH_VARARGS, ""}, {"PyRate_sleep", cyber_PyRate_sleep, METH_VARARGS, ""}, {"PyRate_reset", cyber_PyRate_reset, METH_VARARGS, ""}, {"PyRate_get_cycle_time", cyber_PyRate_get_cycle_time, METH_VARARGS, ""}, {"PyRate_get_expected_cycle_time", cyber_PyRate_get_expected_cycle_time, METH_VARARGS, ""}, {nullptr, nullptr, 0, nullptr} /* sentinel */ }; /// Init function of this module PyMODINIT_FUNC PyInit__cyber_time_wrapper(void) { static struct PyModuleDef module_def = { PyModuleDef_HEAD_INIT, "_cyber_time_wrapper", // Module name. "CyberTime module", // Module doc. -1, // Module size. _cyber_time_methods, // Module methods. nullptr, nullptr, nullptr, nullptr, }; return PyModule_Create(&module_def); }
0
apollo_public_repos/apollo/cyber/python
apollo_public_repos/apollo/cyber/python/internal/py_cyber.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef CYBER_PYTHON_INTERNAL_PY_CYBER_H_ #define CYBER_PYTHON_INTERNAL_PY_CYBER_H_ #include <unistd.h> #include <algorithm> #include <deque> #include <iostream> #include <memory> #include <mutex> #include <string> #include <thread> #include <unordered_map> #include <utility> #include <vector> #include "cyber/cyber.h" #include "cyber/init.h" #include "cyber/message/protobuf_factory.h" #include "cyber/message/py_message.h" #include "cyber/message/raw_message.h" #include "cyber/node/node.h" #include "cyber/node/reader.h" #include "cyber/node/writer.h" #include "cyber/service_discovery/specific_manager/node_manager.h" namespace apollo { namespace cyber { inline bool py_init(const std::string& module_name) { static bool inited = false; if (inited) { AINFO << "cyber already inited."; return true; } if (!Init(module_name.c_str())) { AERROR << "cyber::Init failed:" << module_name; return false; } inited = true; AINFO << "cyber init succ."; return true; } inline bool py_ok() { return OK(); } inline void py_shutdown() { return Clear(); } inline bool py_is_shutdown() { return IsShutdown(); } inline void py_waitforshutdown() { return WaitForShutdown(); } class PyWriter { public: PyWriter(const std::string& channel, const std::string& type, const uint32_t qos_depth, Node* node) : channel_name_(channel), data_type_(type), qos_depth_(qos_depth), node_(node) { std::string proto_desc; message::ProtobufFactory::Instance()->GetDescriptorString(type, &proto_desc); if (proto_desc.empty()) { AWARN << "cpp can't find proto_desc msgtype->" << data_type_; return; } proto::RoleAttributes role_attr; role_attr.set_channel_name(channel_name_); role_attr.set_message_type(data_type_); role_attr.set_proto_desc(proto_desc); auto qos_profile = role_attr.mutable_qos_profile(); qos_profile->set_depth(qos_depth_); writer_ = node_->CreateWriter<message::PyMessageWrap>(role_attr); } int write(const std::string& data) { auto message = std::make_shared<message::PyMessageWrap>(data, data_type_); message->set_type_name(data_type_); return writer_->Write(message); } private: std::string channel_name_; std::string data_type_; uint32_t qos_depth_; Node* node_ = nullptr; std::shared_ptr<Writer<message::PyMessageWrap>> writer_; }; const char RAWDATATYPE[] = "RawData"; class PyReader { public: PyReader(const std::string& channel, const std::string& type, Node* node) : channel_name_(channel), data_type_(type), node_(node), func_(nullptr) { if (data_type_.compare(RAWDATATYPE) == 0) { auto f = [this](const std::shared_ptr<const message::PyMessageWrap>& request) { this->cb(request); }; reader_ = node_->CreateReader<message::PyMessageWrap>(channel, f); } else { auto f = [this](const std::shared_ptr<const message::RawMessage>& request) { this->cb_rawmsg(request); }; reader_rawmsg_ = node_->CreateReader<message::RawMessage>(channel, f); } } void register_func(int (*func)(const char*)) { func_ = func; } std::string read(bool wait = false) { std::string msg(""); std::unique_lock<std::mutex> ul(msg_lock_); if (!cache_.empty()) { msg = std::move(cache_.front()); cache_.pop_front(); } if (!wait) { return msg; } msg_cond_.wait(ul, [this] { return !this->cache_.empty(); }); if (!cache_.empty()) { msg = std::move(cache_.front()); cache_.pop_front(); } return msg; } private: void cb(const std::shared_ptr<const message::PyMessageWrap>& message) { { std::lock_guard<std::mutex> lg(msg_lock_); cache_.push_back(message->data()); } if (func_) { func_(channel_name_.c_str()); } msg_cond_.notify_one(); } void cb_rawmsg(const std::shared_ptr<const message::RawMessage>& message) { { std::lock_guard<std::mutex> lg(msg_lock_); cache_.push_back(message->message); } if (func_) { func_(channel_name_.c_str()); } msg_cond_.notify_one(); } std::string channel_name_; std::string data_type_; Node* node_ = nullptr; int (*func_)(const char*) = nullptr; std::shared_ptr<Reader<message::PyMessageWrap>> reader_ = nullptr; std::deque<std::string> cache_; std::mutex msg_lock_; std::condition_variable msg_cond_; std::shared_ptr<Reader<message::RawMessage>> reader_rawmsg_ = nullptr; }; using PyMsgWrapPtr = std::shared_ptr<message::PyMessageWrap>; class PyService { public: PyService(const std::string& service_name, const std::string& data_type, Node* node) : node_(node), service_name_(service_name), data_type_(data_type), func_(nullptr) { auto f = [this]( const std::shared_ptr<const message::PyMessageWrap>& request, std::shared_ptr<message::PyMessageWrap>& response) { response = this->cb(request); }; service_ = node_->CreateService<message::PyMessageWrap, message::PyMessageWrap>( service_name, f); } void register_func(int (*func)(const char*)) { func_ = func; } std::string read() { std::string msg(""); if (!request_cache_.empty()) { msg = std::move(request_cache_.front()); request_cache_.pop_front(); } return msg; } int write(const std::string& data) { response_cache_.push_back(data); return SUCC; } private: PyMsgWrapPtr cb( const std::shared_ptr<const message::PyMessageWrap>& request) { std::lock_guard<std::mutex> lg(msg_lock_); request_cache_.push_back(request->data()); if (func_) { func_(service_name_.c_str()); } std::string msg(""); if (!response_cache_.empty()) { msg = std::move(response_cache_.front()); response_cache_.pop_front(); } PyMsgWrapPtr response; response.reset(new message::PyMessageWrap(msg, data_type_)); return response; } Node* node_; std::string service_name_; std::string data_type_; int (*func_)(const char*) = nullptr; std::shared_ptr<Service<message::PyMessageWrap, message::PyMessageWrap>> service_; std::mutex msg_lock_; std::deque<std::string> request_cache_; std::deque<std::string> response_cache_; }; class PyClient { public: PyClient(const std::string& name, const std::string& data_type, Node* node) : node_(node), service_name_(name), data_type_(data_type) { client_ = node_->CreateClient<message::PyMessageWrap, message::PyMessageWrap>( name); } std::string send_request(std::string request) { std::shared_ptr<message::PyMessageWrap> m; m.reset(new message::PyMessageWrap(request, data_type_)); auto response = client_->SendRequest(m); if (response == nullptr) { AINFO << "SendRequest:response is null"; return std::string(""); } response->ParseFromString(response->data()); return response->data(); } private: Node* node_; std::string service_name_; std::string data_type_; std::shared_ptr<Client<message::PyMessageWrap, message::PyMessageWrap>> client_; }; class PyNode { public: explicit PyNode(const std::string& node_name) : node_name_(node_name) { node_ = CreateNode(node_name); } void shutdown() { node_.reset(); AINFO << "PyNode " << node_name_ << " exit."; } PyWriter* create_writer(const std::string& channel, const std::string& type, uint32_t qos_depth = 1) { if (node_) { return new PyWriter(channel, type, qos_depth, node_.get()); } AINFO << "Py_Node: node_ is null, new PyWriter failed!"; return nullptr; } void register_message(const std::string& desc) { message::ProtobufFactory::Instance()->RegisterPythonMessage(desc); } PyReader* create_reader(const std::string& channel, const std::string& type) { if (node_) { return new PyReader(channel, type, node_.get()); } return nullptr; } PyService* create_service(const std::string& service, const std::string& type) { if (node_) { return new PyService(service, type, node_.get()); } return nullptr; } PyClient* create_client(const std::string& service, const std::string& type) { if (node_) { return new PyClient(service, type, node_.get()); } return nullptr; } std::shared_ptr<Node> get_node() { return node_; } private: std::string node_name_; std::shared_ptr<Node> node_ = nullptr; }; class PyChannelUtils { public: // Get debugstring of rawmsgdata // Pls make sure the msg_type of rawmsg is matching // Used in cyber_channel echo command static std::string get_debugstring_by_msgtype_rawmsgdata( const std::string& msg_type, const std::string& rawmsgdata) { if (msg_type.empty()) { AERROR << "parse rawmessage the msg_type is null"; return ""; } if (rawmsgdata.empty()) { AERROR << "parse rawmessage the rawmsgdata is null"; return ""; } if (raw_msg_class_ == nullptr) { auto rawFactory = message::ProtobufFactory::Instance(); raw_msg_class_ = rawFactory->GenerateMessageByType(msg_type); } if (raw_msg_class_ == nullptr) { AERROR << "raw_msg_class_ is null"; return ""; } if (!raw_msg_class_->ParseFromString(rawmsgdata)) { AERROR << "Cannot parse the msg [ " << msg_type << " ]"; return ""; } return raw_msg_class_->DebugString(); } static std::string get_msgtype_by_channelname(const std::string& channel_name, uint8_t sleep_s = 0) { if (channel_name.empty()) { AERROR << "channel_name is null"; return ""; } auto topology = service_discovery::TopologyManager::Instance(); sleep(sleep_s); auto channel_manager = topology->channel_manager(); std::string msg_type(""); channel_manager->GetMsgType(channel_name, &msg_type); return msg_type; } static std::vector<std::string> get_active_channels(uint8_t sleep_s = 2) { auto topology = service_discovery::TopologyManager::Instance(); sleep(sleep_s); auto channel_manager = topology->channel_manager(); std::vector<std::string> channels; channel_manager->GetChannelNames(&channels); return channels; } static std::unordered_map<std::string, std::vector<std::string>> get_channels_info(uint8_t sleep_s = 2) { auto topology = service_discovery::TopologyManager::Instance(); sleep(sleep_s); std::vector<proto::RoleAttributes> tmpVec; topology->channel_manager()->GetWriters(&tmpVec); std::unordered_map<std::string, std::vector<std::string>> roles_info; for (auto& attr : tmpVec) { std::string channel_name = attr.channel_name(); std::string msgdata; attr.SerializeToString(&msgdata); roles_info[channel_name].emplace_back(msgdata); } tmpVec.clear(); topology->channel_manager()->GetReaders(&tmpVec); for (auto& attr : tmpVec) { std::string channel_name = attr.channel_name(); std::string msgdata; attr.SerializeToString(&msgdata); roles_info[channel_name].emplace_back(msgdata); } return roles_info; } private: static google::protobuf::Message* raw_msg_class_; }; class PyNodeUtils { public: static std::vector<std::string> get_active_nodes(uint8_t sleep_s = 2) { auto topology = service_discovery::TopologyManager::Instance(); sleep(sleep_s); std::vector<std::string> node_names; std::vector<RoleAttributes> nodes; topology->node_manager()->GetNodes(&nodes); if (nodes.empty()) { AERROR << "no node found."; return node_names; } std::sort(nodes.begin(), nodes.end(), [](const RoleAttributes& na, const RoleAttributes& nb) -> bool { return na.node_name().compare(nb.node_name()) <= 0; }); for (auto& node : nodes) { node_names.emplace_back(node.node_name()); } return node_names; } static std::string get_node_attr(const std::string& node_name, uint8_t sleep_s = 2) { auto topology = service_discovery::TopologyManager::Instance(); sleep(sleep_s); if (!topology->node_manager()->HasNode(node_name)) { AERROR << "no node named: " << node_name; return ""; } std::vector<RoleAttributes> nodes; topology->node_manager()->GetNodes(&nodes); std::string msgdata; for (auto& node_attr : nodes) { if (node_attr.node_name() == node_name) { node_attr.SerializeToString(&msgdata); return msgdata; } } return ""; } static std::vector<std::string> get_readersofnode( const std::string& node_name, uint8_t sleep_s = 2) { std::vector<std::string> reader_channels; auto topology = service_discovery::TopologyManager::Instance(); sleep(sleep_s); if (!topology->node_manager()->HasNode(node_name)) { AERROR << "no node named: " << node_name; return reader_channels; } std::vector<RoleAttributes> readers; auto channel_mgr = topology->channel_manager(); channel_mgr->GetReadersOfNode(node_name, &readers); for (auto& reader : readers) { if (reader.channel_name() == "param_event") { continue; } reader_channels.emplace_back(reader.channel_name()); } return reader_channels; } static std::vector<std::string> get_writersofnode( const std::string& node_name, uint8_t sleep_s = 2) { std::vector<std::string> writer_channels; auto topology = service_discovery::TopologyManager::Instance(); sleep(sleep_s); if (!topology->node_manager()->HasNode(node_name)) { AERROR << "no node named: " << node_name; return writer_channels; } std::vector<RoleAttributes> writers; auto channel_mgr = topology->channel_manager(); channel_mgr->GetWritersOfNode(node_name, &writers); for (auto& writer : writers) { if (writer.channel_name() == "param_event") { continue; } writer_channels.emplace_back(writer.channel_name()); } return writer_channels; } }; class PyServiceUtils { public: static std::vector<std::string> get_active_services(uint8_t sleep_s = 2) { auto topology = service_discovery::TopologyManager::Instance(); sleep(sleep_s); std::vector<std::string> srv_names; std::vector<RoleAttributes> services; topology->service_manager()->GetServers(&services); if (services.empty()) { AERROR << "no service found."; return srv_names; } std::sort(services.begin(), services.end(), [](const RoleAttributes& sa, const RoleAttributes& sb) -> bool { return sa.service_name().compare(sb.service_name()) <= 0; }); for (auto& service : services) { srv_names.emplace_back(service.service_name()); } return srv_names; } static std::string get_service_attr(const std::string& service_name, uint8_t sleep_s = 2) { auto topology = service_discovery::TopologyManager::Instance(); sleep(sleep_s); if (!topology->service_manager()->HasService(service_name)) { AERROR << "no service: " << service_name; return ""; } std::vector<RoleAttributes> services; topology->service_manager()->GetServers(&services); std::string msgdata; for (auto& service_attr : services) { if (service_attr.service_name() == service_name) { service_attr.SerializeToString(&msgdata); return msgdata; } } return ""; } }; } // namespace cyber } // namespace apollo #endif // CYBER_PYTHON_INTERNAL_PY_CYBER_H_
0
apollo_public_repos/apollo/cyber/python
apollo_public_repos/apollo/cyber/python/internal/py_record_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/python/internal/py_record.h" #include <set> #include <string> #include "gtest/gtest.h" #include "cyber/cyber.h" #include "cyber/proto/unit_test.pb.h" namespace apollo { namespace cyber { const char TEST_RECORD_FILE[] = "/tmp/py_record_test.record"; const char CHAN_1[] = "channel/chatter"; const char CHAN_2[] = "/test2"; const char MSG_TYPE[] = "apollo.cyber.proto.Test"; const char PROTO_DESC[] = "1234567890"; const char MSG_DATA[] = "9876543210"; const char TEST_FILE[] = "test.record"; TEST(CyberRecordTest, record_readerwriter) { record::PyRecordWriter rec_writer; rec_writer.SetSizeOfFileSegmentation(0); rec_writer.SetIntervalOfFileSegmentation(0); EXPECT_TRUE(rec_writer.Open(TEST_RECORD_FILE)); rec_writer.WriteChannel(CHAN_1, MSG_TYPE, PROTO_DESC); rec_writer.WriteMessage(CHAN_1, MSG_DATA, 888); EXPECT_EQ(1, rec_writer.GetMessageNumber(CHAN_1)); EXPECT_EQ(MSG_TYPE, rec_writer.GetMessageType(CHAN_1)); EXPECT_EQ(PROTO_DESC, rec_writer.GetProtoDesc(CHAN_1)); rec_writer.Close(); // read record::PyRecordReader rec_reader(TEST_RECORD_FILE); AINFO << "++++ begin reading"; sleep(1); record::BagMessage bag_msg = rec_reader.ReadMessage(); std::set<std::string> channel_list = rec_reader.GetChannelList(); EXPECT_EQ(1, channel_list.size()); EXPECT_EQ(CHAN_1, *channel_list.begin()); const std::string& channel_name = bag_msg.channel_name; EXPECT_EQ(CHAN_1, channel_name); EXPECT_EQ(MSG_DATA, bag_msg.data); EXPECT_EQ(1, rec_reader.GetMessageNumber(channel_name)); EXPECT_EQ(888, bag_msg.timestamp); EXPECT_EQ(MSG_TYPE, bag_msg.data_type); EXPECT_EQ(MSG_TYPE, rec_reader.GetMessageType(channel_name)); const std::string header_str = rec_reader.GetHeaderString(); proto::Header header; header.ParseFromString(header_str); EXPECT_EQ(1, header.major_version()); EXPECT_EQ(0, header.minor_version()); EXPECT_EQ(1, header.chunk_number()); EXPECT_EQ(1, header.channel_number()); EXPECT_TRUE(header.is_complete()); } } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/python
apollo_public_repos/apollo/cyber/python/internal/py_record.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef PYTHON_WRAPPER_PY_RECORD_H_ #define PYTHON_WRAPPER_PY_RECORD_H_ #include <unistd.h> #include <iostream> #include <limits> #include <memory> #include <mutex> #include <set> #include <string> #include <thread> #include "cyber/message/protobuf_factory.h" #include "cyber/message/py_message.h" #include "cyber/message/raw_message.h" #include "cyber/proto/record.pb.h" #include "cyber/record/record_message.h" #include "cyber/record/record_reader.h" #include "cyber/record/record_writer.h" namespace apollo { namespace cyber { namespace record { struct BagMessage { uint64_t timestamp = 0; std::string channel_name = ""; std::string data = ""; std::string data_type = ""; bool end = true; }; class PyRecordReader { public: explicit PyRecordReader(const std::string& file) { record_reader_.reset(new RecordReader(file)); } BagMessage ReadMessage( uint64_t begin_time = 0, uint64_t end_time = std::numeric_limits<uint64_t>::max()) { BagMessage ret_msg; RecordMessage record_message; if (!record_reader_->ReadMessage(&record_message, begin_time, end_time)) { ret_msg.end = true; return ret_msg; } ret_msg.end = false; ret_msg.channel_name = record_message.channel_name; ret_msg.data = record_message.content; ret_msg.timestamp = record_message.time; ret_msg.data_type = record_reader_->GetMessageType(record_message.channel_name); return ret_msg; } uint64_t GetMessageNumber(const std::string& channel_name) { return record_reader_->GetMessageNumber(channel_name); } std::string GetMessageType(const std::string& channel_name) { return record_reader_->GetMessageType(channel_name); } std::string GetProtoDesc(const std::string& channel_name) { return record_reader_->GetProtoDesc(channel_name); } std::string GetHeaderString() { std::string org_data; record_reader_->GetHeader().SerializeToString(&org_data); return org_data; } void Reset() { record_reader_->Reset(); } std::set<std::string> GetChannelList() const { return record_reader_->GetChannelList(); } private: std::unique_ptr<RecordReader> record_reader_; }; class PyRecordWriter { public: bool Open(const std::string& path) { return record_writer_.Open(path); } void Close() { record_writer_.Close(); } bool WriteChannel(const std::string& channel_str, const std::string& type, const std::string& proto_desc) { return record_writer_.WriteChannel(channel_str, type, proto_desc); } bool WriteMessage(const std::string& channel_name, const std::string& rawmessage, uint64_t time, const std::string& proto_desc = "") { return record_writer_.WriteMessage( channel_name, std::make_shared<message::RawMessage>(rawmessage), time, proto_desc); } bool SetSizeOfFileSegmentation(uint64_t size_kilobytes) { return record_writer_.SetSizeOfFileSegmentation(size_kilobytes); } bool SetIntervalOfFileSegmentation(uint64_t time_sec) { return record_writer_.SetIntervalOfFileSegmentation(time_sec); } uint64_t GetMessageNumber(const std::string& channel_name) const { return record_writer_.GetMessageNumber(channel_name); } const std::string& GetMessageType(const std::string& channel_name) const { return record_writer_.GetMessageType(channel_name); } const std::string& GetProtoDesc(const std::string& channel_name) const { return record_writer_.GetProtoDesc(channel_name); } private: RecordWriter record_writer_; }; } // namespace record } // namespace cyber } // namespace apollo #endif // PYTHON_WRAPPER_PY_RECORD_H_
0
apollo_public_repos/apollo/cyber/python
apollo_public_repos/apollo/cyber/python/internal/py_cyber.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/python/internal/py_cyber.h" #include <string> #include <vector> #include <Python.h> using apollo::cyber::Node; using apollo::cyber::PyChannelUtils; using apollo::cyber::PyClient; using apollo::cyber::PyNode; using apollo::cyber::PyReader; using apollo::cyber::PyService; using apollo::cyber::PyServiceUtils; using apollo::cyber::PyWriter; #define PyInt_AsLong PyLong_AsLong #define PyInt_FromLong PyLong_FromLong #define PYOBJECT_NULL_STRING PyBytes_FromStringAndSize("", 0) #define C_STR_TO_PY_BYTES(cstr) \ PyBytes_FromStringAndSize(cstr.c_str(), cstr.size()) google::protobuf::Message *PyChannelUtils::raw_msg_class_ = nullptr; static PyObject *cyber_py_init(PyObject *self, PyObject *args) { char *data = nullptr; Py_ssize_t len = 0; if (!PyArg_ParseTuple(args, const_cast<char *>("s#:cyber_py_init"), &data, &len)) { AERROR << "cyber_py_init:PyArg_ParseTuple failed!"; Py_RETURN_FALSE; } std::string module_name(data, len); bool is_init = apollo::cyber::py_init(module_name); if (is_init) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } static PyObject *cyber_py_ok(PyObject *self, PyObject *args) { bool is_ok = apollo::cyber::py_ok(); if (is_ok) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } static PyObject *cyber_py_shutdown(PyObject *self, PyObject *args) { apollo::cyber::py_shutdown(); Py_INCREF(Py_None); return Py_None; } static PyObject *cyber_py_is_shutdown(PyObject *self, PyObject *args) { bool is_shutdown = apollo::cyber::py_is_shutdown(); if (is_shutdown) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } static PyObject *cyber_py_waitforshutdown(PyObject *self, PyObject *args) { apollo::cyber::py_waitforshutdown(); Py_INCREF(Py_None); return Py_None; } template <typename T> T PyObjectToPtr(PyObject *pyobj, const std::string &type_ptr) { T obj_ptr = (T)PyCapsule_GetPointer(pyobj, type_ptr.c_str()); if (obj_ptr == nullptr) { AERROR << "PyObjectToPtr failed,type->" << type_ptr << "pyobj: " << pyobj; } return obj_ptr; } PyObject *cyber_new_PyWriter(PyObject *self, PyObject *args) { char *channel_name = nullptr; char *data_type = nullptr; uint32_t qos_depth = 1; PyObject *node_pyobj = nullptr; if (!PyArg_ParseTuple(args, const_cast<char *>("ssIO:new_PyWriter"), &channel_name, &data_type, &qos_depth, &node_pyobj)) { Py_INCREF(Py_None); return Py_None; } Node *node = reinterpret_cast<Node *>( PyCapsule_GetPointer(node_pyobj, "apollo_cyber_pynode")); if (nullptr == node) { AERROR << "node is null"; Py_INCREF(Py_None); return Py_None; } PyWriter *writer = new PyWriter((std::string const &)*channel_name, (std::string const &)*data_type, qos_depth, node); PyObject *pyobj_writer = PyCapsule_New(writer, "apollo_cyber_pywriter", nullptr); return pyobj_writer; } PyObject *cyber_delete_PyWriter(PyObject *self, PyObject *args) { PyObject *writer_py = nullptr; if (!PyArg_ParseTuple(args, const_cast<char *>("O:delete_PyWriter"), &writer_py)) { Py_INCREF(Py_None); return Py_None; } PyWriter *writer = reinterpret_cast<PyWriter *>( PyCapsule_GetPointer(writer_py, "apollo_cyber_pywriter")); delete writer; Py_INCREF(Py_None); return Py_None; } PyObject *cyber_PyWriter_write(PyObject *self, PyObject *args) { PyObject *pyobj_writer = nullptr; char *data = nullptr; Py_ssize_t len = 0; if (!PyArg_ParseTuple(args, const_cast<char *>("Os#:cyber_PyWriter_write"), &pyobj_writer, &data, &len)) { AERROR << "cyber_PyWriter_write:cyber_PyWriter_write failed!"; return PyInt_FromLong(1); } PyWriter *writer = PyObjectToPtr<PyWriter *>(pyobj_writer, "apollo_cyber_pywriter"); if (nullptr == writer) { AERROR << "cyber_PyWriter_write:writer ptr is null!"; return PyInt_FromLong(1); } std::string data_str(data, len); int ret = writer->write(data_str); return PyInt_FromLong(ret); } PyObject *cyber_new_PyReader(PyObject *self, PyObject *args) { char *channel_name = nullptr; char *data_type = nullptr; PyObject *node_pyobj = nullptr; if (!PyArg_ParseTuple(args, const_cast<char *>("ssO:new_PyReader"), &channel_name, &data_type, &node_pyobj)) { Py_INCREF(Py_None); return Py_None; } Node *node = reinterpret_cast<Node *>( PyCapsule_GetPointer(node_pyobj, "apollo_cyber_pynode")); if (!node) { AERROR << "node is null"; Py_INCREF(Py_None); return Py_None; } PyReader *reader = new PyReader((std::string const &)*channel_name, (std::string const &)*data_type, node); PyObject *pyobj_reader = PyCapsule_New(reader, "apollo_cyber_pyreader", nullptr); return pyobj_reader; } PyObject *cyber_delete_PyReader(PyObject *self, PyObject *args) { PyObject *reader_py = nullptr; if (!PyArg_ParseTuple(args, const_cast<char *>("O:delete_PyReader"), &reader_py)) { Py_INCREF(Py_None); return Py_None; } PyReader *reader = reinterpret_cast<PyReader *>( PyCapsule_GetPointer(reader_py, "apollo_cyber_pyreader")); delete reader; Py_INCREF(Py_None); return Py_None; } PyObject *cyber_PyReader_read(PyObject *self, PyObject *args) { PyObject *pyobj_reader = nullptr; PyObject *pyobj_iswait = nullptr; if (!PyArg_ParseTuple(args, const_cast<char *>("OO:cyber_PyReader_read"), &pyobj_reader, &pyobj_iswait)) { AERROR << "cyber_PyReader_read:PyArg_ParseTuple failed!"; Py_INCREF(Py_None); return Py_None; } PyReader *reader = PyObjectToPtr<PyReader *>(pyobj_reader, "apollo_cyber_pyreader"); if (nullptr == reader) { AERROR << "cyber_PyReader_read:PyReader ptr is null!"; Py_INCREF(Py_None); return Py_None; } int r = PyObject_IsTrue(pyobj_iswait); if (r == -1) { AERROR << "cyber_PyReader_read:pyobj_iswait is error!"; Py_INCREF(Py_None); return Py_None; } bool wait = (r == 1); const std::string reader_ret = reader->read(wait); return C_STR_TO_PY_BYTES(reader_ret); } PyObject *cyber_PyReader_register_func(PyObject *self, PyObject *args) { PyObject *pyobj_regist_fun = nullptr; PyObject *pyobj_reader = nullptr; int (*callback_fun)(char const *) = (int (*)(char const *))0; if (!PyArg_ParseTuple(args, const_cast<char *>("OO:PyReader_register_func"), &pyobj_reader, &pyobj_regist_fun)) { Py_INCREF(Py_None); return Py_None; } PyReader *reader = PyObjectToPtr<PyReader *>(pyobj_reader, "apollo_cyber_pyreader"); callback_fun = (int (*)(const char *i))PyInt_AsLong(pyobj_regist_fun); if (reader) { AINFO << "reader regist fun"; reader->register_func(callback_fun); } Py_INCREF(Py_None); return Py_None; } PyObject *cyber_new_PyClient(PyObject *self, PyObject *args) { char *channel_name = nullptr; char *data_type = nullptr; PyObject *node_pyobj = nullptr; if (!PyArg_ParseTuple(args, const_cast<char *>("ssO:new_PyClient"), &channel_name, &data_type, &node_pyobj)) { Py_INCREF(Py_None); return Py_None; } Node *node = reinterpret_cast<Node *>( PyCapsule_GetPointer(node_pyobj, "apollo_cyber_pynode")); if (!node) { AERROR << "node is null"; Py_INCREF(Py_None); return Py_None; } PyClient *client = new PyClient((std::string const &)*channel_name, (std::string const &)*data_type, node); PyObject *pyobj_client = PyCapsule_New(client, "apollo_cyber_pyclient", nullptr); return pyobj_client; } PyObject *cyber_delete_PyClient(PyObject *self, PyObject *args) { PyObject *client_py = nullptr; if (!PyArg_ParseTuple(args, const_cast<char *>("O:delete_PyClient"), &client_py)) { Py_INCREF(Py_None); return Py_None; } PyClient *client = reinterpret_cast<PyClient *>( PyCapsule_GetPointer(client_py, "apollo_cyber_pyclient")); delete client; Py_INCREF(Py_None); return Py_None; } PyObject *cyber_PyClient_send_request(PyObject *self, PyObject *args) { PyObject *pyobj_client = nullptr; char *data = nullptr; Py_ssize_t len = 0; if (!PyArg_ParseTuple(args, const_cast<char *>("Os#:PyClient_send_request"), &pyobj_client, &data, &len)) { AERROR << "cyber_PyClient_send_request:PyArg_ParseTuple failed!"; return PYOBJECT_NULL_STRING; } PyClient *client = PyObjectToPtr<PyClient *>(pyobj_client, "apollo_cyber_pyclient"); if (nullptr == client) { AERROR << "cyber_PyClient_send_request:client ptr is null!"; return PYOBJECT_NULL_STRING; } std::string data_str(data, len); ADEBUG << "c++:PyClient_send_request data->[ " << data_str << "]"; const std::string response_str = client->send_request((std::string const &)data_str); ADEBUG << "c++:response data->[ " << response_str << "]"; return C_STR_TO_PY_BYTES(response_str); } PyObject *cyber_new_PyService(PyObject *self, PyObject *args) { char *channel_name = nullptr; char *data_type = nullptr; PyObject *node_pyobj = nullptr; if (!PyArg_ParseTuple(args, const_cast<char *>("ssO:new_PyService"), &channel_name, &data_type, &node_pyobj)) { Py_INCREF(Py_None); return Py_None; } Node *node = reinterpret_cast<Node *>( PyCapsule_GetPointer(node_pyobj, "apollo_cyber_pynode")); if (!node) { AERROR << "node is null"; Py_INCREF(Py_None); return Py_None; } PyService *service = new PyService((std::string const &)*channel_name, (std::string const &)*data_type, node); PyObject *pyobj_service = PyCapsule_New(service, "apollo_cyber_pyservice", nullptr); return pyobj_service; } PyObject *cyber_delete_PyService(PyObject *self, PyObject *args) { PyObject *pyobj_service = nullptr; if (!PyArg_ParseTuple(args, const_cast<char *>("O:delete_PyService"), &pyobj_service)) { Py_INCREF(Py_None); return Py_None; } PyService *service = reinterpret_cast<PyService *>( PyCapsule_GetPointer(pyobj_service, "apollo_cyber_pyservice")); delete service; Py_INCREF(Py_None); return Py_None; } PyObject *cyber_PyService_register_func(PyObject *self, PyObject *args) { PyObject *pyobj_regist_fun = nullptr; PyObject *pyobj_service = nullptr; int (*callback_fun)(char const *) = (int (*)(char const *))0; if (!PyArg_ParseTuple(args, const_cast<char *>("OO:PyService_register_func"), &pyobj_service, &pyobj_regist_fun)) { Py_INCREF(Py_None); return Py_None; } PyService *service = PyObjectToPtr<PyService *>(pyobj_service, "apollo_cyber_pyservice"); callback_fun = (int (*)(const char *i))PyInt_AsLong(pyobj_regist_fun); if (service) { AINFO << "service regist fun"; service->register_func(callback_fun); } Py_INCREF(Py_None); return Py_None; } PyObject *cyber_PyService_read(PyObject *self, PyObject *args) { PyObject *pyobj_service = nullptr; if (!PyArg_ParseTuple(args, const_cast<char *>("O:cyber_PyService_read"), &pyobj_service)) { AERROR << "cyber_PyService_read:PyArg_ParseTuple failed!"; return PYOBJECT_NULL_STRING; } PyService *service = PyObjectToPtr<PyService *>(pyobj_service, "apollo_cyber_pyservice"); if (nullptr == service) { AERROR << "cyber_PyService_read:service ptr is null!"; return PYOBJECT_NULL_STRING; } const std::string reader_ret = service->read(); ADEBUG << "c++:PyService_read -> " << reader_ret; return C_STR_TO_PY_BYTES(reader_ret); } PyObject *cyber_PyService_write(PyObject *self, PyObject *args) { PyObject *pyobj_service = nullptr; char *data = nullptr; Py_ssize_t len = 0; if (!PyArg_ParseTuple(args, const_cast<char *>("Os#:cyber_PyService_write"), &pyobj_service, &data, &len)) { AERROR << "cyber_PyService_write:PyArg_ParseTuple failed!"; return PyInt_FromLong(1); } PyService *service = PyObjectToPtr<PyService *>(pyobj_service, "apollo_cyber_pyservice"); if (nullptr == service) { AERROR << "cyber_PyService_write:writer ptr is null!"; return PyInt_FromLong(1); } std::string data_str(data, len); ADEBUG << "c++:PyService_write data->[ " << data_str << "]"; int ret = service->write((std::string const &)data_str); return PyInt_FromLong(ret); } PyObject *cyber_new_PyNode(PyObject *self, PyObject *args) { char *node_name = nullptr; if (!PyArg_ParseTuple(args, const_cast<char *>("s:new_PyNode"), &node_name)) { Py_INCREF(Py_None); return Py_None; } PyNode *node = new PyNode((std::string const &)node_name); PyObject *pyobj_node = PyCapsule_New(node, "apollo_cyber_pynode", nullptr); return pyobj_node; } PyObject *cyber_delete_PyNode(PyObject *self, PyObject *args) { PyObject *pyobj_node = nullptr; if (!PyArg_ParseTuple(args, const_cast<char *>("O:delete_PyNode"), &pyobj_node)) { Py_INCREF(Py_None); return Py_None; } PyNode *node = reinterpret_cast<PyNode *>( PyCapsule_GetPointer(pyobj_node, "apollo_cyber_pynode")); delete node; Py_INCREF(Py_None); return Py_None; } PyObject *cyber_PyNode_create_writer(PyObject *self, PyObject *args) { PyObject *pyobj_node = nullptr; char *channel_name = nullptr; char *type_name = nullptr; uint32_t qos_depth = 1; if (!PyArg_ParseTuple(args, const_cast<char *>("OssI:PyNode_create_writer"), &pyobj_node, &channel_name, &type_name, &qos_depth)) { AERROR << "cyber_PyNode_create_writer:PyArg_ParseTuple failed!"; Py_INCREF(Py_None); return Py_None; } PyNode *node = PyObjectToPtr<PyNode *>(pyobj_node, "apollo_cyber_pynode"); if (nullptr == node) { AERROR << "cyber_PyNode_create_writer:node ptr is null!"; Py_INCREF(Py_None); return Py_None; } PyWriter *writer = reinterpret_cast<PyWriter *>( (node->create_writer((std::string const &)channel_name, (std::string const &)type_name, qos_depth))); if (nullptr == writer) { AERROR << "cyber_PyNode_create_writer:writer is null!"; Py_INCREF(Py_None); return Py_None; } PyObject *pyobj_writer = PyCapsule_New(writer, "apollo_cyber_pywriter", nullptr); return pyobj_writer; } PyObject *cyber_PyNode_create_reader(PyObject *self, PyObject *args) { char *channel_name = nullptr; char *type_name = nullptr; PyObject *pyobj_node = nullptr; if (!PyArg_ParseTuple(args, const_cast<char *>("Oss:PyNode_create_reader"), &pyobj_node, &channel_name, &type_name)) { AERROR << "PyNode_create_reader:PyArg_ParseTuple failed!"; Py_INCREF(Py_None); return Py_None; } PyNode *node = PyObjectToPtr<PyNode *>(pyobj_node, "apollo_cyber_pynode"); if (nullptr == node) { AERROR << "PyNode_create_reader:node ptr is null!"; Py_INCREF(Py_None); return Py_None; } PyReader *reader = reinterpret_cast<PyReader *>((node->create_reader( (std::string const &)channel_name, (std::string const &)type_name))); ACHECK(reader) << "PyReader is NULL!"; PyObject *pyobj_reader = PyCapsule_New(reader, "apollo_cyber_pyreader", nullptr); return pyobj_reader; } PyObject *cyber_PyNode_create_client(PyObject *self, PyObject *args) { char *channel_name = nullptr; char *type_name = nullptr; PyObject *pyobj_node = nullptr; if (!PyArg_ParseTuple(args, const_cast<char *>("Oss:PyNode_create_client"), &pyobj_node, &channel_name, &type_name)) { AERROR << "PyNode_create_client:PyArg_ParseTuple failed!"; Py_INCREF(Py_None); return Py_None; } PyNode *node = PyObjectToPtr<PyNode *>(pyobj_node, "apollo_cyber_pynode"); if (nullptr == node) { AERROR << "PyNode_create_client:node ptr is null!"; Py_INCREF(Py_None); return Py_None; } PyClient *client = reinterpret_cast<PyClient *>((node->create_client( (std::string const &)channel_name, (std::string const &)type_name))); PyObject *pyobj_client = PyCapsule_New(client, "apollo_cyber_pyclient", nullptr); return pyobj_client; } PyObject *cyber_PyNode_create_service(PyObject *self, PyObject *args) { char *channel_name = nullptr; char *type_name = nullptr; PyObject *pyobj_node = nullptr; if (!PyArg_ParseTuple(args, const_cast<char *>("Oss:cyber_PyNode_create_service"), &pyobj_node, &channel_name, &type_name)) { AERROR << "cyber_PyNode_create_service:PyArg_ParseTuple failed!"; Py_INCREF(Py_None); return Py_None; } PyNode *node = PyObjectToPtr<PyNode *>(pyobj_node, "apollo_cyber_pynode"); if (nullptr == node) { AERROR << "cyber_PyNode_create_service:node ptr is null!"; Py_INCREF(Py_None); return Py_None; } PyService *service = reinterpret_cast<PyService *>((node->create_service( (std::string const &)channel_name, (std::string const &)type_name))); PyObject *pyobj_service = PyCapsule_New(service, "apollo_cyber_pyservice", nullptr); return pyobj_service; } PyObject *cyber_PyNode_shutdown(PyObject *self, PyObject *args) { PyObject *pyobj_node = nullptr; if (!PyArg_ParseTuple(args, const_cast<char *>("O:PyNode_shutdown"), &pyobj_node)) { AERROR << "cyber_PyNode_shutdown:PyNode_shutdown failed!"; Py_INCREF(Py_None); return Py_None; } PyNode *node = PyObjectToPtr<PyNode *>(pyobj_node, "apollo_cyber_pynode"); if (nullptr == node) { AERROR << "cyber_PyNode_shutdown:node ptr is null!"; Py_INCREF(Py_None); return Py_None; } node->shutdown(); Py_INCREF(Py_None); return Py_None; } PyObject *cyber_PyNode_register_message(PyObject *self, PyObject *args) { PyObject *pyobj_node = nullptr; char *desc = nullptr; int len = 0; if (!PyArg_ParseTuple(args, const_cast<char *>("Os#:cyber_PyNode_register_message"), &pyobj_node, &desc, &len)) { AERROR << "cyber_PyNode_register_message: failed!"; Py_INCREF(Py_None); return Py_None; } PyNode *node = PyObjectToPtr<PyNode *>(pyobj_node, "apollo_cyber_pynode"); if (nullptr == node) { AERROR << "cyber_PyNode_register_message:node ptr is null! desc->" << desc; Py_INCREF(Py_None); return Py_None; } std::string desc_str(desc, len); node->register_message((std::string const &)desc_str); Py_INCREF(Py_None); return Py_None; } PyObject *cyber_PyChannelUtils_get_msg_type(PyObject *self, PyObject *args) { char *channel_name = nullptr; Py_ssize_t len = 0; unsigned char sleep_s = 0; if (!PyArg_ParseTuple( args, const_cast<char *>("s#B:cyber_PyChannelUtils_get_msg_type"), &channel_name, &len, &sleep_s)) { AERROR << "cyber_PyChannelUtils_get_msg_type failed!"; return PYOBJECT_NULL_STRING; } std::string channel(channel_name, len); const std::string msg_type = PyChannelUtils::get_msgtype_by_channelname(channel, sleep_s); return C_STR_TO_PY_BYTES(msg_type); } PyObject *cyber_PyChannelUtils_get_debugstring_by_msgtype_rawmsgdata( PyObject *self, PyObject *args) { char *msgtype = nullptr; char *rawdata = nullptr; Py_ssize_t len = 0; if (!PyArg_ParseTuple( args, const_cast<char *>( "ss#:cyber_PyChannelUtils_get_debugstring_by_msgtype_rawmsgdata"), &msgtype, &rawdata, &len)) { AERROR << "cyber_PyChannelUtils_get_debugstring_by_msgtype_rawmsgdata failed!"; return PYOBJECT_NULL_STRING; } std::string raw_data(rawdata, len); const std::string debug_string = PyChannelUtils::get_debugstring_by_msgtype_rawmsgdata(msgtype, raw_data); return C_STR_TO_PY_BYTES(debug_string); } static PyObject *cyber_PyChannelUtils_get_active_channels(PyObject *self, PyObject *args) { unsigned char sleep_s = 0; if (!PyArg_ParseTuple( args, const_cast<char *>("B:cyber_PyChannelUtils_get_active_channels"), &sleep_s)) { AERROR << "cyber_PyChannelUtils_get_active_channels failed!"; Py_INCREF(Py_None); return Py_None; } std::vector<std::string> channel_list = PyChannelUtils::get_active_channels(sleep_s); PyObject *pyobj_list = PyList_New(channel_list.size()); size_t pos = 0; for (const std::string &channel : channel_list) { PyList_SetItem(pyobj_list, pos, Py_BuildValue("s", channel.c_str())); pos++; } return pyobj_list; } // return dict value look like: // { 'channel1':[atrr1, atrr2, atrr3], // 'channel2':[atrr1, atrr2] // } static PyObject *cyber_PyChannelUtils_get_channels_info(PyObject *self, PyObject *args) { auto channelsinfo = PyChannelUtils::get_channels_info(); PyObject *pyobj_channelinfo_dict = PyDict_New(); for (auto &channelinfo : channelsinfo) { std::string channel_name = channelinfo.first; PyObject *bld_name = Py_BuildValue("s", channel_name.c_str()); std::vector<std::string> &roleAttr_list = channelinfo.second; PyObject *pyobj_list = PyList_New(roleAttr_list.size()); size_t pos = 0; for (auto &attr : roleAttr_list) { PyList_SetItem(pyobj_list, pos, C_STR_TO_PY_BYTES(attr)); pos++; } PyDict_SetItem(pyobj_channelinfo_dict, bld_name, pyobj_list); Py_DECREF(bld_name); } return pyobj_channelinfo_dict; } PyObject *cyber_PyNodeUtils_get_active_nodes(PyObject *self, PyObject *args) { unsigned char sleep_s = 0; if (!PyArg_ParseTuple( args, const_cast<char *>("B:cyber_PyNodeUtils_get_active_nodes"), &sleep_s)) { AERROR << "cyber_PyNodeUtils_get_active_nodes failed!"; Py_INCREF(Py_None); return Py_None; } std::vector<std::string> nodes_name = apollo::cyber::PyNodeUtils::get_active_nodes(sleep_s); PyObject *pyobj_list = PyList_New(nodes_name.size()); size_t pos = 0; for (const std::string &name : nodes_name) { PyList_SetItem(pyobj_list, pos, Py_BuildValue("s", name.c_str())); pos++; } return pyobj_list; } PyObject *cyber_PyNodeUtils_get_node_attr(PyObject *self, PyObject *args) { char *node_name = nullptr; Py_ssize_t len = 0; unsigned char sleep_s = 0; if (!PyArg_ParseTuple( args, const_cast<char *>("s#B:cyber_PyNodeUtils_get_node_attr"), &node_name, &len, &sleep_s)) { AERROR << "cyber_PyNodeUtils_get_node_attr failed!"; Py_INCREF(Py_None); return Py_None; } std::string name(node_name, len); const std::string node_attr = apollo::cyber::PyNodeUtils::get_node_attr(name, sleep_s); return C_STR_TO_PY_BYTES(node_attr); } PyObject *cyber_PyNodeUtils_get_readersofnode(PyObject *self, PyObject *args) { char *node_name = nullptr; Py_ssize_t len = 0; unsigned char sleep_s = 0; if (!PyArg_ParseTuple( args, const_cast<char *>("s#B:cyber_PyNodeUtils_get_readersofnode"), &node_name, &len, &sleep_s)) { AERROR << "cyber_PyNodeUtils_get_readersofnode failed!"; Py_INCREF(Py_None); return Py_None; } std::string name(node_name, len); std::vector<std::string> readers_channel = apollo::cyber::PyNodeUtils::get_readersofnode(name, sleep_s); PyObject *pyobj_list = PyList_New(readers_channel.size()); size_t pos = 0; for (const std::string &channel : readers_channel) { PyList_SetItem(pyobj_list, pos, Py_BuildValue("s", channel.c_str())); pos++; } return pyobj_list; } PyObject *cyber_PyNodeUtils_get_writersofnode(PyObject *self, PyObject *args) { char *node_name = nullptr; Py_ssize_t len = 0; unsigned char sleep_s = 0; if (!PyArg_ParseTuple( args, const_cast<char *>("s#B:cyber_PyNodeUtils_get_writersofnode"), &node_name, &len, &sleep_s)) { AERROR << "cyber_PyNodeUtils_get_writersofnode failed!"; Py_INCREF(Py_None); return Py_None; } std::string name(node_name, len); std::vector<std::string> writers_channel = apollo::cyber::PyNodeUtils::get_writersofnode(name, sleep_s); PyObject *pyobj_list = PyList_New(writers_channel.size()); size_t pos = 0; for (const std::string &channel : writers_channel) { PyList_SetItem(pyobj_list, pos, Py_BuildValue("s", channel.c_str())); pos++; } return pyobj_list; } PyObject *cyber_PyServiceUtils_get_active_services(PyObject *self, PyObject *args) { unsigned char sleep_s = 0; if (!PyArg_ParseTuple( args, const_cast<char *>("B:cyber_PyServiceUtils_get_active_services"), &sleep_s)) { AERROR << "cyber_PyServiceUtils_get_active_services failed!"; Py_INCREF(Py_None); return Py_None; } std::vector<std::string> services_name = PyServiceUtils::get_active_services(sleep_s); PyObject *pyobj_list = PyList_New(services_name.size()); size_t pos = 0; for (const std::string &name : services_name) { PyList_SetItem(pyobj_list, pos, Py_BuildValue("s", name.c_str())); pos++; } return pyobj_list; } PyObject *cyber_PyServiceUtils_get_service_attr(PyObject *self, PyObject *args) { char *srv_name = nullptr; Py_ssize_t len = 0; unsigned char sleep_s = 0; if (!PyArg_ParseTuple( args, const_cast<char *>("s#B:cyber_PyServiceUtils_get_service_attr"), &srv_name, &len, &sleep_s)) { AERROR << "cyber_PyServiceUtils_get_service_attr failed!"; Py_INCREF(Py_None); return Py_None; } std::string name(srv_name, len); const std::string srv_attr = PyServiceUtils::get_service_attr(name, sleep_s); return C_STR_TO_PY_BYTES(srv_attr); } ///////////////////////////////////////////////////////////////////// //// global for whole page, init module ///////////////////////////////////////////////////////////////////// static PyMethodDef _cyber_methods[] = { // PyInit fun {"py_init", cyber_py_init, METH_VARARGS, ""}, {"py_ok", cyber_py_ok, METH_NOARGS, ""}, {"py_shutdown", cyber_py_shutdown, METH_NOARGS, ""}, {"py_is_shutdown", cyber_py_is_shutdown, METH_NOARGS, ""}, {"py_waitforshutdown", cyber_py_waitforshutdown, METH_NOARGS, ""}, // PyWriter fun {"new_PyWriter", cyber_new_PyWriter, METH_VARARGS, ""}, {"delete_PyWriter", cyber_delete_PyWriter, METH_VARARGS, ""}, {"PyWriter_write", cyber_PyWriter_write, METH_VARARGS, ""}, // PyReader fun {"new_PyReader", cyber_new_PyReader, METH_VARARGS, ""}, {"delete_PyReader", cyber_delete_PyReader, METH_VARARGS, ""}, {"PyReader_register_func", cyber_PyReader_register_func, METH_VARARGS, ""}, {"PyReader_read", cyber_PyReader_read, METH_VARARGS, ""}, // PyClient fun {"new_PyClient", cyber_new_PyClient, METH_VARARGS, ""}, {"delete_PyClient", cyber_delete_PyClient, METH_VARARGS, ""}, {"PyClient_send_request", cyber_PyClient_send_request, METH_VARARGS, ""}, // PyService fun {"new_PyService", cyber_new_PyService, METH_VARARGS, ""}, {"delete_PyService", cyber_delete_PyService, METH_VARARGS, ""}, {"PyService_register_func", cyber_PyService_register_func, METH_VARARGS, ""}, {"PyService_read", cyber_PyService_read, METH_VARARGS, ""}, {"PyService_write", cyber_PyService_write, METH_VARARGS, ""}, // PyNode fun {"new_PyNode", cyber_new_PyNode, METH_VARARGS, ""}, {"delete_PyNode", cyber_delete_PyNode, METH_VARARGS, ""}, {"PyNode_shutdown", cyber_PyNode_shutdown, METH_VARARGS, ""}, {"PyNode_create_writer", cyber_PyNode_create_writer, METH_VARARGS, ""}, {"PyNode_register_message", cyber_PyNode_register_message, METH_VARARGS, ""}, {"PyNode_create_reader", cyber_PyNode_create_reader, METH_VARARGS, ""}, {"PyNode_create_client", cyber_PyNode_create_client, METH_VARARGS, ""}, {"PyNode_create_service", cyber_PyNode_create_service, METH_VARARGS, ""}, {"PyChannelUtils_get_msg_type", cyber_PyChannelUtils_get_msg_type, METH_VARARGS, ""}, {"PyChannelUtils_get_debugstring_by_msgtype_rawmsgdata", cyber_PyChannelUtils_get_debugstring_by_msgtype_rawmsgdata, METH_VARARGS, ""}, {"PyChannelUtils_get_active_channels", cyber_PyChannelUtils_get_active_channels, METH_VARARGS, ""}, {"PyChannelUtils_get_channels_info", cyber_PyChannelUtils_get_channels_info, METH_VARARGS, ""}, {"PyNodeUtils_get_active_nodes", cyber_PyNodeUtils_get_active_nodes, METH_VARARGS, ""}, {"PyNodeUtils_get_node_attr", cyber_PyNodeUtils_get_node_attr, METH_VARARGS, ""}, {"PyNodeUtils_get_readersofnode", cyber_PyNodeUtils_get_readersofnode, METH_VARARGS, ""}, {"PyNodeUtils_get_writersofnode", cyber_PyNodeUtils_get_writersofnode, METH_VARARGS, ""}, {"PyServiceUtils_get_active_services", cyber_PyServiceUtils_get_active_services, METH_VARARGS, ""}, {"PyServiceUtils_get_service_attr", cyber_PyServiceUtils_get_service_attr, METH_VARARGS, ""}, {nullptr, nullptr, 0, nullptr} /* sentinel */ }; /// Init function of this module PyMODINIT_FUNC PyInit__cyber_wrapper(void) { static struct PyModuleDef module_def = { PyModuleDef_HEAD_INIT, "_cyber_wrapper", // Module name. "Cyber module", // Module doc. -1, // Module size. _cyber_methods, // Module methods. nullptr, nullptr, nullptr, nullptr, }; return PyModule_Create(&module_def); }
0
apollo_public_repos/apollo/cyber/python
apollo_public_repos/apollo/cyber/python/internal/py_parameter.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/python/internal/py_parameter.h" #include <set> #include <string> #include <Python.h> #include "cyber/python/internal/py_cyber.h" using apollo::cyber::Parameter; using apollo::cyber::PyNode; using apollo::cyber::PyParameter; using apollo::cyber::PyParameterClient; using apollo::cyber::PyParameterServer; #define PYOBJECT_NULL_STRING PyBytes_FromStringAndSize("", 0) #define C_STR_TO_PY_BYTES(cstr) \ PyBytes_FromStringAndSize(cstr.c_str(), cstr.size()) template <typename T> T PyObjectToPtr(PyObject* pyobj, const std::string& type_ptr) { T obj_ptr = (T)PyCapsule_GetPointer(pyobj, type_ptr.c_str()); if (obj_ptr == nullptr) { AERROR << "PyObjectToPtr failed,type->" << type_ptr << "pyobj: " << pyobj; } return obj_ptr; } PyObject* cyber_new_PyParameter_noparam(PyObject* self, PyObject* args) { PyParameter* pyparameter = new PyParameter(); return PyCapsule_New(pyparameter, "apollo_cybertron_pyparameter", nullptr); } PyObject* cyber_delete_PyParameter(PyObject* self, PyObject* args) { PyObject* pyobj_param = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("O:cyber_delete_PyParameter"), &pyobj_param)) { Py_INCREF(Py_None); return Py_None; } auto* pyparameter = reinterpret_cast<PyParameter*>( PyCapsule_GetPointer(pyobj_param, "apollo_cybertron_pyparameter")); if (nullptr == pyparameter) { AERROR << "cyber_delete_PyParameter:parameter ptr is null!"; Py_INCREF(Py_None); return Py_None; } delete pyparameter; Py_INCREF(Py_None); return Py_None; } PyObject* cyber_new_PyParameter_int(PyObject* self, PyObject* args) { char* name = nullptr; Py_ssize_t len = 0; int64_t int_value = 0; if (!PyArg_ParseTuple(args, const_cast<char*>("s#L:cyber_new_PyParameter_int"), &name, &len, &int_value)) { AERROR << "cyber_new_PyParameter_int parsetuple failed!"; Py_INCREF(Py_None); return Py_None; } PyParameter* pyparameter = new PyParameter(std::string(name, len), int_value); return PyCapsule_New(pyparameter, "apollo_cybertron_pyparameter", nullptr); } PyObject* cyber_new_PyParameter_double(PyObject* self, PyObject* args) { char* name = nullptr; Py_ssize_t len = 0; double double_value = 0; if (!PyArg_ParseTuple(args, const_cast<char*>("s#d:cyber_new_PyParameter_double"), &name, &len, &double_value)) { AERROR << "cyber_new_PyParameter_double parsetuple failed!"; Py_INCREF(Py_None); return Py_None; } PyParameter* pyparameter = new PyParameter(std::string(name, len), double_value); return PyCapsule_New(pyparameter, "apollo_cybertron_pyparameter", nullptr); } PyObject* cyber_new_PyParameter_string(PyObject* self, PyObject* args) { char* name = nullptr; char* string_param = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("ss:cyber_new_PyParameter_string"), &name, &string_param)) { AERROR << "cyber_new_PyParameter_string parsetuple failed!"; Py_INCREF(Py_None); return Py_None; } PyParameter* pyparameter = new PyParameter(std::string(name), std::string(string_param)); return PyCapsule_New(pyparameter, "apollo_cybertron_pyparameter", nullptr); } PyObject* cyber_PyParameter_type_name(PyObject* self, PyObject* args) { PyObject* pyobj_param = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("O:cyber_PyParameter_type_name"), &pyobj_param)) { AERROR << "cyber_PyParameter_type_name failed!"; return PYOBJECT_NULL_STRING; } auto* param = reinterpret_cast<PyParameter*>( PyCapsule_GetPointer(pyobj_param, "apollo_cybertron_pyparameter")); if (nullptr == param) { AERROR << "cyber_PyParameter_type_name ptr is null!"; return PYOBJECT_NULL_STRING; } const std::string type = param->type_name(); return C_STR_TO_PY_BYTES(type); } PyObject* cyber_PyParameter_descriptor(PyObject* self, PyObject* args) { PyObject* pyobj_param = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("O:cyber_PyParameter_descriptor"), &pyobj_param)) { AERROR << "cyber_PyParameter_descriptor failed!"; return PYOBJECT_NULL_STRING; } auto* param = reinterpret_cast<PyParameter*>( PyCapsule_GetPointer(pyobj_param, "apollo_cybertron_pyparameter")); if (nullptr == param) { AERROR << "cyber_PyParameter_descriptor ptr is null!"; return PYOBJECT_NULL_STRING; } const std::string desc = param->descriptor(); return C_STR_TO_PY_BYTES(desc); } PyObject* cyber_PyParameter_name(PyObject* self, PyObject* args) { PyObject* pyobj_param = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("O:cyber_PyParameter_name"), &pyobj_param)) { AERROR << "cyber_PyParameter_name failed!"; return PYOBJECT_NULL_STRING; } auto* param = reinterpret_cast<PyParameter*>( PyCapsule_GetPointer(pyobj_param, "apollo_cybertron_pyparameter")); if (nullptr == param) { AERROR << "cyber_PyParameter_name ptr is null!"; return PYOBJECT_NULL_STRING; } const std::string name = param->name(); return C_STR_TO_PY_BYTES(name); } PyObject* cyber_PyParameter_debug_string(PyObject* self, PyObject* args) { PyObject* pyobj_param = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("O:cyber_PyParameter_debug_string"), &pyobj_param)) { AERROR << "cyber_PyParameter_debug_string failed!"; return PYOBJECT_NULL_STRING; } auto* param = reinterpret_cast<PyParameter*>( PyCapsule_GetPointer(pyobj_param, "apollo_cybertron_pyparameter")); if (nullptr == param) { AERROR << "cyber_PyParameter_debug_string ptr is null!"; return PYOBJECT_NULL_STRING; } const std::string debug_string = param->debug_string(); return C_STR_TO_PY_BYTES(debug_string); } PyObject* cyber_PyParameter_as_string(PyObject* self, PyObject* args) { PyObject* pyobj_param = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("O:cyber_PyParameter_as_string"), &pyobj_param)) { AERROR << "cyber_PyParameter_as_string failed!"; return PYOBJECT_NULL_STRING; } auto* param = reinterpret_cast<PyParameter*>( PyCapsule_GetPointer(pyobj_param, "apollo_cybertron_pyparameter")); if (nullptr == param) { AERROR << "cyber_PyParameter_as_string ptr is null!"; return PYOBJECT_NULL_STRING; } std::string debug_string = param->as_string(); return C_STR_TO_PY_BYTES(debug_string); } PyObject* cyber_PyParameter_as_double(PyObject* self, PyObject* args) { PyObject* pyobj_param = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("O:cyber_PyParameter_as_double"), &pyobj_param)) { AERROR << "cyber_PyParameter_as_double failed!"; return PyFloat_FromDouble(0.0); } auto* param = reinterpret_cast<PyParameter*>( PyCapsule_GetPointer(pyobj_param, "apollo_cybertron_pyparameter")); if (nullptr == param) { AERROR << "cyber_PyParameter_as_double ptr is null!"; return PyFloat_FromDouble(0.0); } double dTemp = param->as_double(); return PyFloat_FromDouble(dTemp); } PyObject* cyber_PyParameter_as_int64(PyObject* self, PyObject* args) { PyObject* pyobj_param = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("O:cyber_PyParameter_as_int64"), &pyobj_param)) { AERROR << "cyber_PyParameter_as_int64 failed!"; return PyLong_FromLongLong(0); } auto* param = reinterpret_cast<PyParameter*>( PyCapsule_GetPointer(pyobj_param, "apollo_cybertron_pyparameter")); if (nullptr == param) { AERROR << "cyber_PyParameter_as_int64 ptr is null!"; return PyLong_FromLongLong(0); } int64_t lTemp = param->as_int64(); return PyLong_FromLongLong(lTemp); } // PyParameterClient PyObject* cyber_new_PyParameterClient(PyObject* self, PyObject* args) { PyObject* pyobj_node = nullptr; char* service_node_name = nullptr; Py_ssize_t len = 0; if (!PyArg_ParseTuple(args, const_cast<char*>("Os#:cyber_new_PyParameterClient"), &pyobj_node, &service_node_name, &len)) { AERROR << "cyber_new_PyParameterClient parsetuple failed!"; Py_INCREF(Py_None); return Py_None; } PyNode* pynode = PyObjectToPtr<PyNode*>(pyobj_node, "apollo_cyber_pynode"); if (nullptr == pynode) { AERROR << "pynode ptr is null!"; Py_INCREF(Py_None); return Py_None; } auto node = pynode->get_node(); if (nullptr == node) { AERROR << "node ptr is null!"; Py_INCREF(Py_None); return Py_None; } PyParameterClient* pyparameter_clt = new PyParameterClient(node, std::string(service_node_name, len)); return PyCapsule_New(pyparameter_clt, "apollo_cybertron_pyparameterclient", nullptr); } PyObject* cyber_delete_PyParameterClient(PyObject* self, PyObject* args) { PyObject* pyobj_param = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("O:cyber_delete_PyParameterClient"), &pyobj_param)) { AERROR << "cyber_delete_PyParameterClient parsetuple failed!"; Py_INCREF(Py_None); return Py_None; } PyParameterClient* pyparameter_clt = reinterpret_cast<PyParameterClient*>( PyCapsule_GetPointer(pyobj_param, "apollo_cybertron_pyparameterclient")); if (nullptr == pyparameter_clt) { AERROR << "cyber_delete_PyParameterClient:pyparameter_clt ptr is null!"; Py_INCREF(Py_None); return Py_None; } delete pyparameter_clt; Py_INCREF(Py_None); return Py_None; } PyObject* cyber_PyParameter_clt_set_parameter(PyObject* self, PyObject* args) { PyObject* pyobj_param_clt = nullptr; PyObject* pyobj_param = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("OO:cyber_PyParameter_set_parameter"), &pyobj_param_clt, &pyobj_param)) { AERROR << "cyber_PyParameter_set_parameter parsetuple failed!"; Py_RETURN_FALSE; } PyParameterClient* pyparam_clt = PyObjectToPtr<PyParameterClient*>( pyobj_param_clt, "apollo_cybertron_pyparameterclient"); if (nullptr == pyparam_clt) { AERROR << "pyparam_clt ptr is null!"; Py_RETURN_FALSE; } PyParameter* pyparam = PyObjectToPtr<PyParameter*>(pyobj_param, "apollo_cybertron_pyparameter"); if (nullptr == pyparam) { AERROR << "pyparam ptr is null!"; Py_RETURN_FALSE; } if (!pyparam_clt->set_parameter(pyparam->get_param())) { Py_RETURN_FALSE; } else { Py_RETURN_TRUE; } } PyObject* cyber_PyParameter_clt_get_parameter(PyObject* self, PyObject* args) { char* name = nullptr; Py_ssize_t len = 0; PyObject* pyobj_param_clt = nullptr; if (!PyArg_ParseTuple( args, const_cast<char*>("Os#:cyber_PyParameter_get_parameter"), &pyobj_param_clt, &name, &len)) { AERROR << "cyber_PyParameter_get_parameter parsetuple failed!"; Py_INCREF(Py_None); return Py_None; } PyParameterClient* pyparam_clt = PyObjectToPtr<PyParameterClient*>( pyobj_param_clt, "apollo_cybertron_pyparameterclient"); if (nullptr == pyparam_clt) { AERROR << "pyparam_clt ptr is null!"; Py_INCREF(Py_None); return Py_None; } Parameter* param = new Parameter(); std::string str_param = std::string(name, len); if (!pyparam_clt->get_parameter(str_param, param)) { AERROR << "pyparam_clt get_parameter is false!"; Py_INCREF(Py_None); return Py_None; } PyParameter* pyparameter = new PyParameter(param); return PyCapsule_New(pyparameter, "apollo_cybertron_pyparameter", nullptr); } PyObject* cyber_PyParameter_clt_get_parameter_list(PyObject* self, PyObject* args) { PyObject* pyobj_param_clt = nullptr; if (!PyArg_ParseTuple( args, const_cast<char*>("O:cyber_PyParameter_clt_get_parameter_list"), &pyobj_param_clt)) { AERROR << "cyber_PyParameter_clt_get_parameter_list:PyArg_ParseTuple failed!"; Py_INCREF(Py_None); return Py_None; } auto* pyparam_clt = reinterpret_cast<PyParameterClient*>(PyCapsule_GetPointer( pyobj_param_clt, "apollo_cybertron_pyparameterclient")); if (nullptr == pyparam_clt) { AERROR << "cyber_PyParameter_clt_get_parameter_list pyparam_clt is null!"; Py_INCREF(Py_None); return Py_None; } std::vector<Parameter> param_list; pyparam_clt->list_parameters(&param_list); PyObject* pyobj_list = PyList_New(param_list.size()); size_t pos = 0; for (auto& param : param_list) { Parameter* param_ptr = new Parameter(param); PyParameter* pyparameter = new PyParameter(param_ptr); PyObject* pyobj_param = PyCapsule_New(pyparameter, "apollo_cybertron_pyparameter", nullptr); PyList_SetItem(pyobj_list, pos, pyobj_param); pos++; } return pyobj_list; } // PyParameterServer PyObject* cyber_new_PyParameterServer(PyObject* self, PyObject* args) { PyObject* pyobj_node = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("O:cyber_new_PyParameterServer"), &pyobj_node)) { AERROR << "cyber_new_PyParameterServer parsetuple failed!"; Py_INCREF(Py_None); return Py_None; } PyNode* pynode = PyObjectToPtr<PyNode*>(pyobj_node, "apollo_cyber_pynode"); if (nullptr == pynode) { AERROR << "pynode ptr is null!"; Py_INCREF(Py_None); return Py_None; } auto node = pynode->get_node(); if (nullptr == node) { AERROR << "node ptr is null!"; Py_INCREF(Py_None); return Py_None; } PyParameterServer* pyparameter_srv = new PyParameterServer(node); return PyCapsule_New(pyparameter_srv, "apollo_cybertron_pyparameterserver", nullptr); } PyObject* cyber_delete_PyParameterServer(PyObject* self, PyObject* args) { PyObject* pyobj_param = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("O:cyber_delete_PyParameterServer"), &pyobj_param)) { AERROR << "cyber_delete_PyParameterServer parsetuple failed!"; Py_INCREF(Py_None); return Py_None; } PyParameterServer* pyparameter_srv = reinterpret_cast<PyParameterServer*>( PyCapsule_GetPointer(pyobj_param, "apollo_cybertron_pyparameterserver")); if (nullptr == pyparameter_srv) { AERROR << "cyber_delete_PyParameterServer:pyparameter_srv ptr is null!"; Py_INCREF(Py_None); return Py_None; } delete pyparameter_srv; Py_INCREF(Py_None); return Py_None; } PyObject* cyber_PyParameter_srv_set_parameter(PyObject* self, PyObject* args) { PyObject* pyobj_param_srv = nullptr; PyObject* pyobj_param = nullptr; if (!PyArg_ParseTuple(args, const_cast<char*>("OO:cyber_PyParameter_set_parameter"), &pyobj_param_srv, &pyobj_param)) { AERROR << "cyber_PyParameter_set_parameter parsetuple failed!"; Py_INCREF(Py_None); return Py_None; } PyParameterServer* pyparam_srv = PyObjectToPtr<PyParameterServer*>( pyobj_param_srv, "apollo_cybertron_pyparameterserver"); if (nullptr == pyparam_srv) { AERROR << "pyparam_srv ptr is null!"; Py_INCREF(Py_None); return Py_None; } PyParameter* pyparam = PyObjectToPtr<PyParameter*>(pyobj_param, "apollo_cybertron_pyparameter"); if (nullptr == pyparam) { AERROR << "pyparam ptr is null!"; Py_INCREF(Py_None); return Py_None; } pyparam_srv->set_parameter(pyparam->get_param()); Py_INCREF(Py_None); return Py_None; } PyObject* cyber_PyParameter_srv_get_parameter(PyObject* self, PyObject* args) { char* name = nullptr; Py_ssize_t len = 0; PyObject* pyobj_param_srv = nullptr; if (!PyArg_ParseTuple( args, const_cast<char*>("Os#:cyber_PyParameter_get_parameter"), &pyobj_param_srv, &name, &len)) { AERROR << "cyber_PyParameter_get_parameter parsetuple failed!"; Py_INCREF(Py_None); return Py_None; } PyParameterServer* pyparam_srv = PyObjectToPtr<PyParameterServer*>( pyobj_param_srv, "apollo_cybertron_pyparameterserver"); if (nullptr == pyparam_srv) { AERROR << "pyparam_srv ptr is null!"; Py_INCREF(Py_None); return Py_None; } Parameter* param = new Parameter(); std::string str_param = std::string(name, len); if (!pyparam_srv->get_parameter(str_param, param)) { AERROR << "pyparam_srv get_parameter is false!"; Py_INCREF(Py_None); return Py_None; } PyParameter* pyparameter = new PyParameter(param); return PyCapsule_New(pyparameter, "apollo_cybertron_pyparameter", nullptr); } PyObject* cyber_PyParameter_srv_get_parameter_list(PyObject* self, PyObject* args) { PyObject* pyobj_param_srv = nullptr; if (!PyArg_ParseTuple( args, const_cast<char*>("O:cyber_PyParameter_srv_get_parameter_list"), &pyobj_param_srv)) { AERROR << "cyber_PyParameter_srv_get_parameter_list:PyArg_ParseTuple failed!"; Py_INCREF(Py_None); return Py_None; } auto* pyparam_srv = reinterpret_cast<PyParameterServer*>(PyCapsule_GetPointer( pyobj_param_srv, "apollo_cybertron_pyparameterserver")); if (nullptr == pyparam_srv) { AERROR << "cyber_PyParameter_srv_get_parameter_list pyparam_srv is null!"; Py_INCREF(Py_None); return Py_None; } std::vector<Parameter> param_list; pyparam_srv->list_parameters(&param_list); PyObject* pyobj_list = PyList_New(param_list.size()); size_t pos = 0; for (auto& param : param_list) { Parameter* param_ptr = new Parameter(param); PyParameter* pyparameter = new PyParameter(param_ptr); PyObject* pyobj_param = PyCapsule_New(pyparameter, "apollo_cybertron_pyparameter", nullptr); PyList_SetItem(pyobj_list, pos, pyobj_param); pos++; } return pyobj_list; } static PyMethodDef _cyber_parameter_methods[] = { {"new_PyParameter_noparam", cyber_new_PyParameter_noparam, METH_NOARGS, ""}, {"delete_PyParameter", cyber_delete_PyParameter, METH_VARARGS, ""}, {"new_PyParameter_int", cyber_new_PyParameter_int, METH_VARARGS, ""}, {"new_PyParameter_double", cyber_new_PyParameter_double, METH_VARARGS, ""}, {"new_PyParameter_string", cyber_new_PyParameter_string, METH_VARARGS, ""}, {"PyParameter_type_name", cyber_PyParameter_type_name, METH_VARARGS, ""}, {"PyParameter_descriptor", cyber_PyParameter_descriptor, METH_VARARGS, ""}, {"PyParameter_name", cyber_PyParameter_name, METH_VARARGS, ""}, {"PyParameter_debug_string", cyber_PyParameter_debug_string, METH_VARARGS, ""}, {"PyParameter_as_string", cyber_PyParameter_as_string, METH_VARARGS, ""}, {"PyParameter_as_double", cyber_PyParameter_as_double, METH_VARARGS, ""}, {"PyParameter_as_int64", cyber_PyParameter_as_int64, METH_VARARGS, ""}, {"new_PyParameterClient", cyber_new_PyParameterClient, METH_VARARGS, ""}, {"delete_PyParameterClient", cyber_delete_PyParameterClient, METH_VARARGS, ""}, {"PyParameter_clt_set_parameter", cyber_PyParameter_clt_set_parameter, METH_VARARGS, ""}, {"PyParameter_clt_get_parameter", cyber_PyParameter_clt_get_parameter, METH_VARARGS, ""}, {"PyParameter_clt_get_parameter_list", cyber_PyParameter_clt_get_parameter_list, METH_VARARGS, ""}, {"new_PyParameterServer", cyber_new_PyParameterServer, METH_VARARGS, ""}, {"delete_PyParameterServer", cyber_delete_PyParameterServer, METH_VARARGS, ""}, {"PyParameter_srv_set_parameter", cyber_PyParameter_srv_set_parameter, METH_VARARGS, ""}, {"PyParameter_srv_get_parameter", cyber_PyParameter_srv_get_parameter, METH_VARARGS, ""}, {"PyParameter_srv_get_parameter_list", cyber_PyParameter_srv_get_parameter_list, METH_VARARGS, ""}, {nullptr, nullptr, 0, nullptr} /* sentinel */ }; /// Init function of this module PyMODINIT_FUNC PyInit__cyber_parameter_wrapper(void) { static struct PyModuleDef module_def = { PyModuleDef_HEAD_INIT, "_cyber_parameter_wrapper", // Module name. "CyberParameter module", // Module doc. -1, // Module size. _cyber_parameter_methods, // Module methods. nullptr, nullptr, nullptr, nullptr, }; return PyModule_Create(&module_def); }
0
apollo_public_repos/apollo/cyber/python
apollo_public_repos/apollo/cyber/python/internal/BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library", "cc_test") load("//tools/install:install.bzl", "install") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) install( name = "install", library_dest = "cyber/python/cyber/python/internal", #data = [":runtime_files"], #data_dest = "cyber/python/internal", targets = [ ":_cyber_wrapper.so", ":_cyber_record_wrapper.so", ":_cyber_time_wrapper.so", ":_cyber_timer_wrapper.so", ":_cyber_parameter_wrapper.so", ], #rename = { # "cyber/python/internal/internal.BUILD": "BUILD" #} ) #filegroup( # name = "runtime_files", # srcs = ["internal.BUILD"] #) cc_binary( name = "_cyber_wrapper.so", srcs = ["py_cyber.cc"], linkshared = True, linkstatic = True, deps = [ ":py_cyber", ], ) cc_library( name = "py_cyber", srcs = ["py_cyber.cc"], hdrs = ["py_cyber.h"], #alwayslink = True, deps = [ "//cyber:cyber_core", "@local_config_python//:python_headers", "@local_config_python//:python_lib", ], ) cc_test( name = "py_cyber_test", size = "small", srcs = ["py_cyber_test.cc"], deps = [ ":py_cyber", "//cyber/proto:unit_test_cc_proto", "@com_google_googletest//:gtest", ], linkstatic = True, ) cc_binary( name = "_cyber_record_wrapper.so", srcs = ["py_record.cc"], linkshared = True, linkstatic = True, deps = [ ":py_record", ], ) cc_library( name = "py_record", srcs = ["py_record.cc"], hdrs = ["py_record.h"], #alwayslink = True, deps = [ "//cyber:cyber_core", "//cyber/message:py_message", "@local_config_python//:python_headers", "@local_config_python//:python_lib", ], ) cc_test( name = "py_record_test", size = "small", srcs = ["py_record_test.cc"], deps = [ ":py_record", "//cyber/proto:unit_test_cc_proto", "@com_google_googletest//:gtest_main", #"@fastrtps", ], linkstatic = True, ) cc_binary( name = "_cyber_time_wrapper.so", srcs = ["py_time.cc"], linkshared = True, linkstatic = True, deps = [ ":py_time", ], ) cc_library( name = "py_time", srcs = ["py_time.cc"], hdrs = ["py_time.h"], #alwayslink = True, deps = [ "//cyber:cyber_core", "@fastrtps", "@local_config_python//:python_headers", "@local_config_python//:python_lib", ], ) cc_binary( name = "_cyber_timer_wrapper.so", srcs = ["py_timer.cc"], linkshared = True, linkstatic = True, deps = [ ":py_timer", ], ) cc_library( name = "py_timer", srcs = ["py_timer.cc"], hdrs = ["py_timer.h"], #alwayslink = True, deps = [ "//cyber:cyber_core", "@local_config_python//:python_headers", "@local_config_python//:python_lib", ], ) cc_binary( name = "_cyber_parameter_wrapper.so", srcs = ["py_parameter.cc"], linkshared = True, linkstatic = True, deps = [ ":py_parameter", ], ) cc_library( name = "py_parameter", srcs = ["py_parameter.cc"], hdrs = ["py_parameter.h"], #alwayslink = True, deps = [ ":py_cyber", "//cyber:cyber_core", "@local_config_python//:python_headers", "@local_config_python//:python_lib", ], ) cpplint()
0
apollo_public_repos/apollo/cyber/python
apollo_public_repos/apollo/cyber/python/internal/internal.BUILD
package(default_visibility = ["//visibility:public"]) exports_files( [ "_cyber_wrapper.so", "_cyber_record_wrapper.so", "_cyber_time_wrapper.so", "_cyber_timer_wrapper.so", "_cyber_parameter_wrapper.so" ] )
0
apollo_public_repos/apollo/cyber/python
apollo_public_repos/apollo/cyber/python/internal/py_parameter.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef CYBER_PYTHON_INTERNAL_PY_PARAMETER_H_ #define CYBER_PYTHON_INTERNAL_PY_PARAMETER_H_ #include <unistd.h> #include <functional> #include <memory> #include <string> #include <vector> #include "cyber/cyber.h" #include "cyber/init.h" #include "cyber/parameter/parameter.h" #include "cyber/parameter/parameter_client.h" #include "cyber/parameter/parameter_server.h" namespace apollo { namespace cyber { class PyParameter { public: PyParameter() {} explicit PyParameter(Parameter* param) : parameter_(*param) {} PyParameter(const std::string& name, const int64_t int_value) : parameter_(name, int_value) {} PyParameter(const std::string& name, const double double_value) : parameter_(name, double_value) {} PyParameter(const std::string& name, const std::string& string_value) : parameter_(name, string_value) {} PyParameter(const std::string& name, const std::string& msg_str, const std::string& full_name, const std::string& proto_desc) : parameter_(name, msg_str, full_name, proto_desc) {} uint type() { return parameter_.Type(); } std::string type_name() { return parameter_.TypeName(); } std::string descriptor() { return parameter_.Descriptor(); } std::string name() { return parameter_.Name(); } int64_t as_int64() { return parameter_.AsInt64(); } double as_double() { return parameter_.AsDouble(); } std::string as_string() { return parameter_.AsString(); } std::string debug_string() { return parameter_.DebugString(); } Parameter& get_param() { return parameter_; } private: Parameter parameter_; }; class PyParameterClient { public: PyParameterClient(const std::shared_ptr<Node>& node, const std::string& service_node_name) : parameter_clt_(node, service_node_name) {} bool set_parameter(const Parameter& parameter) { return parameter_clt_.SetParameter(parameter); } bool get_parameter(const std::string& param_name, Parameter* parameter) { return parameter_clt_.GetParameter(param_name, parameter); } bool list_parameters(std::vector<Parameter>* parameters) { return parameter_clt_.ListParameters(parameters); } private: ParameterClient parameter_clt_; }; class PyParameterServer { public: explicit PyParameterServer(const std::shared_ptr<Node>& node) : parameter_srv_(node) {} void set_parameter(const Parameter& parameter) { parameter_srv_.SetParameter(parameter); } bool get_parameter(const std::string& param_name, Parameter* parameter) { return parameter_srv_.GetParameter(param_name, parameter); } void list_parameters(std::vector<Parameter>* parameters) { parameter_srv_.ListParameters(parameters); } private: ParameterServer parameter_srv_; }; } // namespace cyber } // namespace apollo #endif // CYBER_PYTHON_INTERNAL_PY_PARAMETER_H_
0
apollo_public_repos/apollo/cyber/python
apollo_public_repos/apollo/cyber/python/internal/py_cyber_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/python/internal/py_cyber.h" #include <memory> #include <string> #include "gtest/gtest.h" #include "cyber/cyber.h" #include "cyber/message/py_message.h" #include "cyber/proto/unit_test.pb.h" namespace apollo { namespace cyber { TEST(PyCyberTest, init_ok) { EXPECT_TRUE(py_ok()); EXPECT_TRUE(OK()); } TEST(PyCyberTest, create_reader) { EXPECT_TRUE(OK()); proto::Chatter chat; PyNode node("listener"); std::unique_ptr<PyReader> pr( node.create_reader("channel/chatter", chat.GetTypeName())); EXPECT_EQ("apollo.cyber.proto.Chatter", chat.GetTypeName()); EXPECT_NE(pr, nullptr); pr->register_func([](const char* channel_name) -> int { AINFO << "recv->[ " << channel_name << " ]"; return 0; }); } TEST(PyCyberTest, create_writer) { EXPECT_TRUE(OK()); auto msgChat = std::make_shared<proto::Chatter>(); PyNode node("talker"); std::unique_ptr<PyWriter> pw( node.create_writer("channel/chatter", msgChat->GetTypeName(), 10)); EXPECT_NE(pw, nullptr); EXPECT_TRUE(OK()); uint64_t seq = 5; msgChat->set_timestamp(Time::Now().ToNanosecond()); msgChat->set_lidar_timestamp(Time::Now().ToNanosecond()); msgChat->set_seq(seq++); msgChat->set_content("Hello, apollo!"); std::string org_data; msgChat->SerializeToString(&org_data); EXPECT_TRUE(pw->write(org_data)); } } // namespace cyber } // namespace apollo int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); apollo::cyber::py_init("py_init_test"); const int ret_val = RUN_ALL_TESTS(); apollo::cyber::py_shutdown(); return ret_val; }
0
apollo_public_repos/apollo/cyber/python
apollo_public_repos/apollo/cyber/python/cyber_py3/cyber_py3.BUILD
load("@rules_python//python:defs.bzl", "py_library") package(default_visibility = ["//visibility:public"]) pb_deps = ["@com_google_protobuf//:protobuf_python"] py_library( name = "cyber_time", srcs = ["cyber_time.py"], data = [ "//python/internal:_cyber_time_wrapper.so", "//python/internal:_cyber_wrapper.so", ], deps = pb_deps ) py_library( name = "cyber_timer", srcs = ["cyber_timer.py"], data = [ "//python/internal:_cyber_timer_wrapper.so", ], deps = pb_deps ) py_library( name = "cyber", srcs = ["cyber.py"], data = [ "//python/internal:_cyber_wrapper.so", ], deps = pb_deps ) py_library( name = "parameter", srcs = ["parameter.py"], data = [ "//python/internal:_cyber_parameter_wrapper.so", ], deps = pb_deps ) py_library( name = "record", srcs = ["record.py"], data = [ "//python/internal:_cyber_record_wrapper.so", ], deps = pb_deps )
0
apollo_public_repos/apollo/cyber/python
apollo_public_repos/apollo/cyber/python/cyber_py3/__init__.py
#!/usr/bin/env python3 # **************************************************************************** # Copyright 2019 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # **************************************************************************** import sys if sys.version_info[0] < 3: sys.stderr.write(''' You are running Python2 while importing Python3 Cyber wrapper! Please change to "import cyber_py.xyz" accordingly.\n''') sys.exit(1)
0
apollo_public_repos/apollo/cyber/python
apollo_public_repos/apollo/cyber/python/cyber_py3/cyber.py
#!/usr/bin/env python3 # **************************************************************************** # Copyright 2019 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # **************************************************************************** # -*- coding: utf-8 -*- """Module for init environment.""" import ctypes import importlib import os import sys import threading import time from google.protobuf.descriptor_pb2 import FileDescriptorProto PY_CALLBACK_TYPE = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_char_p) PY_CALLBACK_TYPE_T = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_char_p) # init vars wrapper_lib_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../internal')) sys.path.append(wrapper_lib_path) _CYBER = importlib.import_module('_cyber_wrapper') ## # @brief init cyber environment. # @param module_name Used as the log file name. # # @return Success is True, otherwise False. def init(module_name="cyber_py"): """ init cyber environment. """ return _CYBER.py_init(module_name) def ok(): """ is cyber envi ok. """ return _CYBER.py_ok() def shutdown(): """ shutdown cyber envi. """ return _CYBER.py_shutdown() def is_shutdown(): """ is cyber shutdown. """ return _CYBER.py_is_shutdown() def waitforshutdown(): """ wait until the cyber is shutdown. """ return _CYBER.py_waitforshutdown() # //////////////////////////////class////////////////////////////// class Writer(object): """ Class for cyber writer wrapper. """ def __init__(self, name, writer, data_type): self.name = name self.writer = writer self.data_type = data_type ## # @brief write message. # # @param data is a message type. # # @return Success is 0, otherwise False. def write(self, data): """ writer message string """ return _CYBER.PyWriter_write(self.writer, data.SerializeToString()) class Reader(object): """ Class for cyber reader wrapper. """ def __init__(self, name, reader, data_type): self.name = name self.reader = reader self.data_type = data_type class Client(object): """ Class for cyber service client wrapper. """ def __init__(self, client, data_type): self.client = client self.data_type = data_type ## # @brief send request message to service. # # @param data is a message type. # # @return None or response from service. def send_request(self, data): """ send request to service """ response_str = _CYBER.PyClient_send_request( self.client, data.SerializeToString()) if len(response_str) == 0: return None response = self.data_type() response.ParseFromString(response_str) return response class Node(object): """ Class for cyber Node wrapper. """ def __init__(self, name): self.node = _CYBER.new_PyNode(name) self.list_writer = [] self.list_reader = [] self.subs = {} self.pubs = {} self.list_client = [] self.list_service = [] self.mutex = threading.Lock() self.callbacks = {} self.services = {} def __del__(self): # print("+++ node __del___") for writer in self.list_writer: _CYBER.delete_PyWriter(writer) for reader in self.list_reader: _CYBER.delete_PyReader(reader) for c in self.list_client: _CYBER.delete_PyClient(c) for s in self.list_service: _CYBER.delete_PyService(s) _CYBER.delete_PyNode(self.node) ## # @brief register proto message by proto descriptor file. # # @param file_desc object about datatype.DESCRIPTOR.file . def register_message(self, file_desc): """ register proto message desc file. """ for dep in file_desc.dependencies: self.register_message(dep) proto = FileDescriptorProto() file_desc.CopyToProto(proto) proto.name = file_desc.name desc_str = proto.SerializeToString() _CYBER.PyNode_register_message(self.node, desc_str) ## # @brief create a channel writer for send message to another channel. # # @param name is the channel name. # @param data_type is message class for serialization # @param qos_depth is a queue size, which defines the size of the cache. # # @return return the writer object. def create_writer(self, name, data_type, qos_depth=1): """ create a channel writer for send message to another channel. """ self.register_message(data_type.DESCRIPTOR.file) datatype = data_type.DESCRIPTOR.full_name writer = _CYBER.PyNode_create_writer(self.node, name, datatype, qos_depth) self.list_writer.append(writer) return Writer(name, writer, datatype) def reader_callback(self, name): sub = self.subs[name.decode('utf8')] msg_str = _CYBER.PyReader_read(sub[0], False) if len(msg_str) > 0: if sub[3] != "RawData": proto = sub[3]() proto.ParseFromString(msg_str) else: # print "read rawdata-> ",sub[3] proto = msg_str if sub[2] is None: sub[1](proto) else: sub[1](proto, sub[2]) return 0 ## # @brief create a channel reader for receive message from another channel. # # @param name the channel name to read. # @param data_type message class for serialization # @param callback function to call (fn(data)) when data is received. If # args is set, the function must accept the args as a second argument, # i.e. fn(data, args) # @param args additional arguments to pass to the callback # # @return return the writer object. def create_reader(self, name, data_type, callback, args=None): """ create a channel reader for receive message from another channel. """ self.mutex.acquire() if name in self.subs.keys(): self.mutex.release() return None self.mutex.release() # datatype = data_type.DESCRIPTOR.full_name reader = _CYBER.PyNode_create_reader( self.node, name, str(data_type)) if reader is None: return None self.list_reader.append(reader) sub = (reader, callback, args, data_type, False) self.mutex.acquire() self.subs[name] = sub self.mutex.release() fun_reader_cb = PY_CALLBACK_TYPE(self.reader_callback) self.callbacks[name] = fun_reader_cb f_ptr = ctypes.cast(self.callbacks[name], ctypes.c_void_p).value _CYBER.PyReader_register_func(reader, f_ptr) return Reader(name, reader, data_type) def create_rawdata_reader(self, name, callback, args=None): """ Create RawData reader:listener RawMessage """ return self.create_reader(name, "RawData", callback, args) ## # @brief create client for the c/s. # # @param name the service name. # @param request_data_type the request message type. # @param response_data_type the response message type. # # @return the client object. def create_client(self, name, request_data_type, response_data_type): datatype = request_data_type.DESCRIPTOR.full_name c = _CYBER.PyNode_create_client(self.node, name, str(datatype)) self.list_client.append(c) return Client(c, response_data_type) def service_callback(self, name): # Temporary workaround for cyber_py3 examples: service & client v = self.services[name.decode("utf-8")] msg_str = _CYBER.PyService_read(v[0]) if (len(msg_str) > 0): proto = v[3]() proto.ParseFromString(msg_str) response = None if v[2] is None: response = v[1](proto) else: response = v[1](proto, v[2]) _CYBER.PyService_write(v[0], response.SerializeToString()) return 0 ## # @brief create client for the c/s. # # @param name the service name. # @param req_data_type the request message type. # @param res_data_type the response message type. # @param callback function to call (fn(data)) when data is received. If # args is set, the function must accept the args as a second argument, # i.e. fn(data, args) # @param args additional arguments to pass to the callback. # # @return return the service object. def create_service(self, name, req_data_type, res_data_type, callback, args=None): self.mutex.acquire() if name in self.services.keys(): self.mutex.release() return None self.mutex.release() datatype = req_data_type.DESCRIPTOR.full_name s = _CYBER.PyNode_create_service(self.node, name, str(datatype)) self.list_service.append(s) v = (s, callback, args, req_data_type, False) self.mutex.acquire() self.services[name] = v self.mutex.release() f = PY_CALLBACK_TYPE(self.service_callback) self.callbacks[name] = f f_ptr = ctypes.cast(f, ctypes.c_void_p).value _CYBER.PyService_register_func(s, f_ptr) return s def spin(self): """ spin for every 0.002s. """ while not _CYBER.py_is_shutdown(): time.sleep(0.002) class ChannelUtils(object): @staticmethod ## # @brief Parse rawmsg from rawmsg data by message type. # # @param msg_type message type. # @param rawmsgdata rawmsg data. # # @return a human readable form of this message. For debugging and # other purposes. def get_debugstring_rawmsgdata(msg_type, rawmsgdata): return _CYBER.PyChannelUtils_get_debugstring_by_msgtype_rawmsgdata(msg_type, rawmsgdata) @staticmethod ## # @brief Parse rawmsg from channel name. # # @param channel_name channel name. # @param sleep_s wait time for topo discovery. # # @return return the messsage type of this channel. def get_msgtype(channel_name, sleep_s=2): return _CYBER.PyChannelUtils_get_msg_type(channel_name, sleep_s) @staticmethod ## # @brief Get all active channel names # # @param sleep_s wait time for topo discovery. # # @return all active channel names. def get_channels(sleep_s=2): return _CYBER.PyChannelUtils_get_active_channels(sleep_s) @staticmethod ## # @brief Get the active channel info. # # @param sleep_s wait time for topo discovery. # # @return all active channels info. {'channel1':[], 'channel2':[]} . def get_channels_info(sleep_s=2): return _CYBER.PyChannelUtils_get_channels_info(sleep_s) class NodeUtils(object): @staticmethod ## # @brief Get all active node names. # # @param sleep_s wait time for topo discovery. # # @return all active node names. def get_nodes(sleep_s=2): return _CYBER.PyNodeUtils_get_active_nodes(sleep_s) @staticmethod ## # @brief Get node attribute by the node name. # # @param node_name node name. # @param sleep_s wait time for topo discovery. # # @return the node's attribute. def get_node_attr(node_name, sleep_s=2): return _CYBER.PyNodeUtils_get_node_attr(node_name, sleep_s) @staticmethod ## # @brief Get node's reader channel names # # @param node_name the node name. # @param sleep_s wait time for topo discovery. # # @return node's reader channel names. def get_readersofnode(node_name, sleep_s=2): return _CYBER.PyNodeUtils_get_readersofnode(node_name, sleep_s) @staticmethod ## # @brief Get node's writer channel names. # # @param node_name the node name. # @param sleep_s wait time for topo discovery. # # @return node's writer channel names. def get_writersofnode(node_name, sleep_s=2): return _CYBER.PyNodeUtils_get_writersofnode(node_name, sleep_s) class ServiceUtils(object): @staticmethod ## # @brief Get all active service names. # # @param sleep_s wait time for topo discovery. # # @return all active service names. def get_services(sleep_s=2): return _CYBER.PyServiceUtils_get_active_services(sleep_s) @staticmethod ## # @brief Get service attribute by the service name. # # @param service_name service name. # @param sleep_s wait time for topo discovery. # # @return the service's attribute. def get_service_attr(service_name, sleep_s=2): return _CYBER.PyServiceUtils_get_service_attr(service_name, sleep_s)
0
apollo_public_repos/apollo/cyber/python
apollo_public_repos/apollo/cyber/python/cyber_py3/cyber_timer.py
#!/usr/bin/env python3 # **************************************************************************** # Copyright 2019 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # **************************************************************************** # -*- coding: utf-8 -*- """Module for init environment.""" import ctypes import importlib import os import sys PY_TIMER_CB_TYPE = ctypes.CFUNCTYPE(ctypes.c_void_p) # init vars wrapper_lib_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../internal')) sys.path.append(wrapper_lib_path) _CYBER_TIMER = importlib.import_module('_cyber_timer_wrapper') class Timer(object): """ Class for cyber timer wrapper. """ ## # @brief Used to perform oneshot or periodic timing tasks # # @param period The period of the timer, unit is ms. # @param callback The tasks that the timer needs to perform. # @param oneshot 1:perform the callback only after the first timing cycle # 0:perform the callback every timed period def __init__(self, period=None, callback=None, oneshot=None): if period is None and callback is None and oneshot is None: self.timer = _CYBER_TIMER.new_PyTimer_noparam() else: self.timer_cb = PY_TIMER_CB_TYPE(callback) self.f_ptr_cb = ctypes.cast(self.timer_cb, ctypes.c_void_p).value self.timer = _CYBER_TIMER.new_PyTimer( period, self.f_ptr_cb, oneshot) def __del__(self): _CYBER_TIMER.delete_PyTimer(self.timer) ## # @brief set the option of timer. # # @param period The period of the timer, unit is ms. # @param callback The tasks that the timer needs to perform. # @param oneshot 1:perform the callback only after the first timing cycle # 0:perform the callback every timed period def set_option(self, period, callback, oneshot=0): self.timer_cb = PY_TIMER_CB_TYPE(callback) self.f_ptr_cb = ctypes.cast(self.timer_cb, ctypes.c_void_p).value _CYBER_TIMER.PyTimer_set_option( self.timer, period, self.f_ptr_cb, oneshot) ## # @brief start the timer def start(self): _CYBER_TIMER.PyTimer_start(self.timer) ## # @brief stop the timer def stop(self): _CYBER_TIMER.PyTimer_stop(self.timer)
0
apollo_public_repos/apollo/cyber/python
apollo_public_repos/apollo/cyber/python/cyber_py3/record.py
#!/usr/bin/env python3 # **************************************************************************** # Copyright 2019 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # **************************************************************************** # -*- coding: utf-8 -*- """Module for wrapper cyber record.""" import collections import importlib import os import sys from google.protobuf.descriptor_pb2 import FileDescriptorProto # Refer to the _cyber_record_wrapper.so with relative path so that it can be # always addressed as a part of the runfiles. wrapper_lib_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../internal')) sys.path.append(wrapper_lib_path) _CYBER_RECORD = importlib.import_module('_cyber_record_wrapper') PyBagMessage = collections.namedtuple('PyBagMessage', 'topic message data_type timestamp') class RecordReader(object): """ Class for cyber RecordReader wrapper. """ ## # @brief the constructor function. # # @param file_name the record file name. def __init__(self, file_name): self.record_reader = _CYBER_RECORD.new_PyRecordReader(file_name) def __del__(self): _CYBER_RECORD.delete_PyRecordReader(self.record_reader) ## # @brief Read message from bag file. # # @param start_time the start time to read. # @param end_time the end time to read. # # @return return (channnel, data, data_type, timestamp) def read_messages(self, start_time=0, end_time=18446744073709551615): while True: message = _CYBER_RECORD.PyRecordReader_ReadMessage( self.record_reader, start_time, end_time) if not message["end"]: yield PyBagMessage(message["channel_name"], message["data"], message["data_type"], message["timestamp"]) else: # print "No message more." break ## # @brief Return message count of the channel in current record file. # # @param channel_name the channel name. # # @return return the message count. def get_messagenumber(self, channel_name): return _CYBER_RECORD.PyRecordReader_GetMessageNumber( self.record_reader, channel_name) ## # @brief Get the corresponding message type of channel. # # @param channel_name channel name. # # @return return the name of ther string type. def get_messagetype(self, channel_name): return _CYBER_RECORD.PyRecordReader_GetMessageType( self.record_reader, channel_name).decode('utf-8') def get_protodesc(self, channel_name): """ Return message protodesc. """ return _CYBER_RECORD.PyRecordReader_GetProtoDesc( self.record_reader, channel_name) def get_headerstring(self): """ Return message header string. """ return _CYBER_RECORD.PyRecordReader_GetHeaderString(self.record_reader) def reset(self): """ Return reset. """ return _CYBER_RECORD.PyRecordReader_Reset(self.record_reader) def get_channellist(self): """ Return current channel names list. """ return _CYBER_RECORD.PyRecordReader_GetChannelList(self.record_reader) class RecordWriter(object): """ Class for cyber RecordWriter wrapper. """ ## # @brief the constructor function. # # @param file_segmentation_size_kb size to segment the file, 0 is no segmentation. # @param file_segmentation_interval_sec size to segment the file, 0 is no segmentation. def __init__(self, file_segmentation_size_kb=0, file_segmentation_interval_sec=0): self.record_writer = _CYBER_RECORD.new_PyRecordWriter() _CYBER_RECORD.PyRecordWriter_SetSizeOfFileSegmentation( self.record_writer, file_segmentation_size_kb) _CYBER_RECORD.PyRecordWriter_SetIntervalOfFileSegmentation( self.record_writer, file_segmentation_interval_sec) def __del__(self): _CYBER_RECORD.delete_PyRecordWriter(self.record_writer) ## # @brief Open record file for write. # # @param path the file path. # # @return Success is True, other False. def open(self, path): return _CYBER_RECORD.PyRecordWriter_Open(self.record_writer, path) ## # @brief Close record file. def close(self): """ Close record file. """ _CYBER_RECORD.PyRecordWriter_Close(self.record_writer) ## # @brief Writer channel by channelname, typename, protodesc. # # @param channel_name the channel name to write # @param type_name a string of message type name. # @param proto_desc the message descriptor. # # @return Success is True, other False. def write_channel(self, channel_name, type_name, proto_desc): """ Writer channel by channelname,typename,protodesc """ return _CYBER_RECORD.PyRecordWriter_WriteChannel( self.record_writer, channel_name, type_name, proto_desc) ## # @brief Writer msg: channelname, data, writer time. # # @param channel_name channel name to write. # @param data when raw is True, data processed as a rawdata, other it needs to SerializeToString # @param time message time. # @param raw the flag implies data whether or not a rawdata. # # @return Success is True, other False. def write_message(self, channel_name, data, time, raw=True): """ Writer msg:channelname,rawmsg,writer time """ if raw: return _CYBER_RECORD.PyRecordWriter_WriteMessage( self.record_writer, channel_name, data, time, "") file_desc = data.DESCRIPTOR.file proto = FileDescriptorProto() file_desc.CopyToProto(proto) proto.name = file_desc.name desc_str = proto.SerializeToString() return _CYBER_RECORD.PyRecordWriter_WriteMessage( self.record_writer, channel_name, data.SerializeToString(), time, desc_str) def set_size_fileseg(self, size_kilobytes): """ Return filesegment size. """ return _CYBER_RECORD.PyRecordWriter_SetSizeOfFileSegmentation( self.record_writer, size_kilobytes) def set_intervaltime_fileseg(self, time_sec): """ Return file interval time. """ return _CYBER_RECORD.PyRecordWriter_SetIntervalOfFileSegmentation( self.record_writer, time_sec) def get_messagenumber(self, channel_name): """ Return message count. """ return _CYBER_RECORD.PyRecordWriter_GetMessageNumber( self.record_writer, channel_name) def get_messagetype(self, channel_name): """ Return message type. """ return _CYBER_RECORD.PyRecordWriter_GetMessageType( self.record_writer, channel_name).decode('utf-8') def get_protodesc(self, channel_name): """ Return message protodesc. """ return _CYBER_RECORD.PyRecordWriter_GetProtoDesc( self.record_writer, channel_name)
0
apollo_public_repos/apollo/cyber/python
apollo_public_repos/apollo/cyber/python/cyber_py3/BUILD
load("@rules_python//python:defs.bzl", "py_library") load("//tools/install:install.bzl", "install", "install_files") package(default_visibility = ["//visibility:public"]) filegroup( name = "runtime_files", srcs = glob([ "*.py", ]) + ["cyber_py3.BUILD"] ) install( name = "cyber_python_library", data = [":runtime_files"], data_dest = "cyber/python/cyber/python/cyber_py3" ) py_library( name = "cyber_time", srcs = ["cyber_time.py"], data = [ "//cyber/python/internal:_cyber_time_wrapper.so", "//cyber/python/internal:_cyber_wrapper.so", ], ) py_library( name = "cyber_timer", srcs = ["cyber_timer.py"], data = [ "//cyber/python/internal:_cyber_timer_wrapper.so", ], ) py_library( name = "cyber", srcs = ["cyber.py"], data = [ "//cyber/python/internal:_cyber_wrapper.so", ], ) py_library( name = "parameter", srcs = ["parameter.py"], data = [ "//cyber/python/internal:_cyber_parameter_wrapper.so", ], ) py_library( name = "record", srcs = ["record.py"], data = [ "//cyber/python/internal:_cyber_record_wrapper.so", ], )
0
apollo_public_repos/apollo/cyber/python
apollo_public_repos/apollo/cyber/python/cyber_py3/parameter.py
#!/usr/bin/env python3 # **************************************************************************** # Copyright 2019 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # **************************************************************************** # -*- coding: utf-8 -*- """Module for init environment.""" import importlib import os import sys # init vars CYBER_PATH = os.environ.get('CYBER_PATH', '/apollo/cyber') CYBER_DIR = os.path.split(CYBER_PATH)[0] wrapper_lib_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../internal')) sys.path.append(wrapper_lib_path) _CYBER_PARAM = importlib.import_module('_cyber_parameter_wrapper') class Parameter(object): """ Class for Parameter wrapper. """ def __init__(self, name, value=None): if (name is not None and value is None): self.param = name elif (name is None and value is None): self.param = _CYBER_PARAM.new_PyParameter_noparam() elif isinstance(value, int): self.param = _CYBER_PARAM.new_PyParameter_int(name, value) elif isinstance(value, float): self.param = _CYBER_PARAM.new_PyParameter_double(name, value) elif isinstance(value, str): self.param = _CYBER_PARAM.new_PyParameter_string(name, value) else: print("type is not supported: ", type(value)) def __del__(self): _CYBER_PARAM.delete_PyParameter(self.param) def type_name(self): """ return Parameter typename """ return _CYBER_PARAM.PyParameter_type_name(self.param) def descriptor(self): """ return Parameter descriptor """ return _CYBER_PARAM.PyParameter_descriptor(self.param) def name(self): """ return Parameter name """ return _CYBER_PARAM.PyParameter_name(self.param) def debug_string(self): """ return Parameter debug string """ return _CYBER_PARAM.PyParameter_debug_string(self.param) def as_string(self): """ return native value """ return _CYBER_PARAM.PyParameter_as_string(self.param) def as_double(self): """ return native value """ return _CYBER_PARAM.PyParameter_as_double(self.param) def as_int64(self): """ return native value """ return _CYBER_PARAM.PyParameter_as_int64(self.param) class ParameterClient(object): """ Class for ParameterClient wrapper. """ ## # @brief constructor the ParameterClient by a node and the parameter server node name. # # @param node a node to create client. # @param server_node_name the parameter server's node name. def __init__(self, node, server_node_name): self.param_clt = _CYBER_PARAM.new_PyParameterClient( node.node, server_node_name) def __del__(self): _CYBER_PARAM.delete_PyParameterClient(self.param_clt) def set_parameter(self, param): """ set parameter, param is Parameter. """ return _CYBER_PARAM.PyParameter_clt_set_parameter(self.param_clt, param.param) def get_parameter(self, param_name): """ get Parameter by param name param_name. """ return Parameter(_CYBER_PARAM.PyParameter_clt_get_parameter(self.param_clt, param_name)) def get_paramslist(self): """ get all params of the server_node_name parameterserver. """ pycapsulelist = _CYBER_PARAM.PyParameter_clt_get_parameter_list( self.param_clt) param_list = [] for capsuleobj in pycapsulelist: param_list.append(Parameter(capsuleobj)) return param_list class ParameterServer(object): """ Class for ParameterServer wrapper. """ ## # @brief constructor the ParameterServer by the node object. # # @param node the node to support the parameter server. def __init__(self, node): self.param_srv = _CYBER_PARAM.new_PyParameterServer(node.node) def __del__(self): _CYBER_PARAM.delete_PyParameterServer(self.param_srv) def set_parameter(self, param): """ set parameter, param is Parameter. """ return _CYBER_PARAM.PyParameter_srv_set_parameter(self.param_srv, param.param) def get_parameter(self, param_name): """ get Parameter by param name param_name. """ return Parameter(_CYBER_PARAM.PyParameter_srv_get_parameter(self.param_srv, param_name)) def get_paramslist(self): """ get all params of this parameterserver. """ pycapsulelist = _CYBER_PARAM.PyParameter_srv_get_parameter_list( self.param_srv) param_list = [] for capsuleobj in pycapsulelist: param_list.append(Parameter(capsuleobj)) return param_list
0
apollo_public_repos/apollo/cyber/python
apollo_public_repos/apollo/cyber/python/cyber_py3/cyber_time.py
#!/usr/bin/env python3 # **************************************************************************** # Copyright 2019 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # **************************************************************************** # -*- coding: utf-8 -*- """Module for init environment.""" import importlib import os import sys # init vars wrapper_lib_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../internal')) sys.path.append(wrapper_lib_path) _CYBER = importlib.import_module('_cyber_wrapper') _CYBER_TIME = importlib.import_module('_cyber_time_wrapper') class Duration(object): """ Class for cyber Duration wrapper. """ def __init__(self, other): if isinstance(other, int): self.nanoseconds_ = other elif isinstance(other, float): self.nanoseconds_ = other * 1000000000 elif isinstance(other, Duration): self.nanoseconds_ = other.nanoseconds_ self.duration_ = _CYBER_TIME.new_PyDuration(int(self.nanoseconds_)) def __del__(self): _CYBER_TIME.delete_PyDuration(self.duration_) def sleep(self): """ sleep for the amount of time specified by the duration. """ _CYBER_TIME.PyDuration_sleep(self.duration_) def __str__(self): return str(self.nanoseconds_) def to_sec(self): """ convert to second. """ return float(self.nanoseconds_) / 1000000000 def to_nsec(self): """ convert to nanosecond. """ return self.nanoseconds_ def iszero(self): return self.nanoseconds_ == 0 def __add__(self, other): return Duration(self.nanoseconds_ + other.nanoseconds_) def __radd__(self, other): return Duration(self.nanoseconds_ + other.nanoseconds_) def __sub__(self, other): return Duration(self.nanoseconds_ - other.nanoseconds_) def __lt__(self, other): return self.nanoseconds_ < other.nanoseconds_ def __gt__(self, other): return self.nanoseconds_ > other.nanoseconds_ def __le__(self, other): return self.nanoseconds_ <= other.nanoseconds_ def __ge__(self, other): return self.nanoseconds_ >= other.nanoseconds_ def __eq__(self, other): return self.nanoseconds_ == other.nanoseconds_ def __ne__(self, other): return self.nanoseconds_ != other.nanoseconds_ class Time(object): """ Class for cyber time wrapper. """ ## # @brief Constructor, creates a Time. # # @param other float means seconds unit. # int means nanoseconds. def __init__(self, other): nanoseconds = 0 if isinstance(other, int): nanoseconds = other elif isinstance(other, float): nanoseconds = other * 1000000000 elif isinstance(other, Time): nanoseconds = other.to_nsec() self.time = _CYBER_TIME.new_PyTime(int(nanoseconds)) def __del__(self): _CYBER_TIME.delete_PyTime(self.time) def __str__(self): return str(self.to_nsec()) def iszero(self): return self.to_nsec() == 0 @staticmethod def now(): """ return current time. """ # print _CYBER_TIME.PyTime_now() # print type(_CYBER_TIME.PyTime_now()) time_now = Time(_CYBER_TIME.PyTime_now()) return time_now @staticmethod def mono_time(): mono_time = Time(_CYBER_TIME.PyTime_mono_time()) return mono_time def to_sec(self): """ convert to second. """ return _CYBER_TIME.PyTime_to_sec(self.time) def to_nsec(self): """ convert to nanosecond. """ return _CYBER_TIME.PyTime_to_nsec(self.time) def sleep_until(self, cyber_time): """ sleep until time. """ if isinstance(time, Time): return _CYBER_TIME.PyTime_sleep_until(self.time, cyber_time.to_nsec()) return NotImplemented def __sub__(self, other): if isinstance(other, Time): return Duration(self.to_nsec() - other.to_nsec()) else: isinstance(other, Duration) return Time(self.to_nsec() - other.to_nsec()) def __add__(self, other): return Time(self.to_nsec() + other.to_nsec()) def __radd__(self, other): return Time(self.to_nsec() + other.to_nsec()) def __lt__(self, other): return self.to_nsec() < other.to_nsec() def __gt__(self, other): return self.to_nsec() > other.to_nsec() def __le__(self, other): return self.to_nsec() <= other.to_nsec() def __ge__(self, other): return self.to_nsec() >= other.to_nsec() def __eq__(self, other): return self.to_nsec() == other.to_nsec() def __ne__(self, other): return self.to_nsec() != other.to_nsec() class Rate(object): """ Class for cyber Rate wrapper. Help run loops at a desired frequency. """ ## # @brief Constructor, creates a Rate. # # @param other float means frequency the desired rate to run at in Hz. # int means the expected_cycle_time. def __init__(self, other): if isinstance(other, int): self.rate_ = _CYBER_TIME.new_PyRate(other) elif isinstance(other, float): self.rate_ = _CYBER_TIME.new_PyRate(int(1.0 / other)) elif isinstance(other, Duration): self.rate_ = _CYBER_TIME.new_PyRate(other.to_nsec()) def __del__(self): _CYBER_TIME.delete_PyRate(self.rate_) def __str__(self): return "cycle_time = %s, exp_cycle_time = %s" % (str(self.get_cycle_time()), str(self.get_expected_cycle_time())) def sleep(self): """ Sleeps for any leftover time in a cycle. """ _CYBER_TIME.PyRate_sleep(self.rate_) def reset(self): """ Sets the start time for the rate to now. """ _CYBER_TIME.PyRate_PyRate_reset(self.rate_) def get_cycle_time(self): """ Get the actual run time of a cycle from start to sleep. """ return Duration(_CYBER_TIME.PyRate_get_cycle_time(self.rate_)) def get_expected_cycle_time(self): """ Get the expected cycle time. """ return Duration(_CYBER_TIME.PyRate_get_expected_cycle_time(self.rate_))
0
apollo_public_repos/apollo/cyber/python/cyber_py3
apollo_public_repos/apollo/cyber/python/cyber_py3/test/record_test.py
#!/usr/bin/env python3 # **************************************************************************** # Copyright 2019 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # **************************************************************************** # -*- coding: utf-8 -*- """Module for test record.""" import unittest from cyber.proto import record_pb2 from cyber.python.cyber_py3 import record from cyber.proto.simple_pb2 import SimpleMessage TEST_RECORD_FILE = "/tmp/test02.record" CHAN_1 = "channel/chatter" MSG_TYPE = "apollo.common.util.test.SimpleMessage" PROTO_DESC = b"1234567890" MSG_DATA = b"0123456789" TIME = 999 class TestRecord(unittest.TestCase): """ Class for record unit test. """ def test_record_writer_read(self): """ unit test of record. """ # writer fwriter = record.RecordWriter() fwriter.set_size_fileseg(0) fwriter.set_intervaltime_fileseg(0) self.assertTrue(fwriter.open(TEST_RECORD_FILE)) fwriter.write_channel(CHAN_1, MSG_TYPE, PROTO_DESC) fwriter.write_message(CHAN_1, MSG_DATA, TIME) self.assertEqual(1, fwriter.get_messagenumber(CHAN_1)) self.assertEqual(MSG_TYPE, fwriter.get_messagetype(CHAN_1)) self.assertEqual(PROTO_DESC, fwriter.get_protodesc(CHAN_1)) fwriter.close() # reader fread = record.RecordReader(TEST_RECORD_FILE) channel_list = fread.get_channellist() self.assertEqual(1, len(channel_list)) self.assertEqual(CHAN_1, channel_list[0]) header = record_pb2.Header() header.ParseFromString(fread.get_headerstring()) self.assertEqual(1, header.major_version) self.assertEqual(0, header.minor_version) self.assertEqual(1, header.chunk_number) self.assertEqual(1, header.channel_number) self.assertTrue(header.is_complete) for channelname, msg, datatype, timestamp in fread.read_messages(): self.assertEqual(CHAN_1, channelname) self.assertEqual(MSG_DATA, msg) self.assertEqual(TIME, timestamp) self.assertEqual(1, fread.get_messagenumber(channelname)) self.assertEqual(MSG_TYPE, datatype) self.assertEqual(MSG_TYPE, fread.get_messagetype(channelname)) if __name__ == '__main__': unittest.main()
0
apollo_public_repos/apollo/cyber/python/cyber_py3
apollo_public_repos/apollo/cyber/python/cyber_py3/test/parameter_test.py
#!/usr/bin/env python3 # **************************************************************************** # Copyright 2019 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # **************************************************************************** # -*- coding: utf-8 -*- """Module for test node.""" import time import unittest from cyber.python.cyber_py3 import cyber from cyber.python.cyber_py3 import parameter PARAM_SERVICE_NAME = "global_parameter_service" class TestParams(unittest.TestCase): """ Class for node unit test. """ @classmethod def setUpClass(cls): cyber.init() @classmethod def tearDownClass(cls): cyber.shutdown() def test_params(self): param1 = parameter.Parameter("author_name", "WanderingEarth") param2 = parameter.Parameter("author_age", 5000) param3 = parameter.Parameter("author_score", 888.88) test_node = cyber.Node(PARAM_SERVICE_NAME) srv = parameter.ParameterServer(test_node) node_handle = cyber.Node("service_client_node") clt = parameter.ParameterClient(test_node, PARAM_SERVICE_NAME) clt.set_parameter(param1) clt.set_parameter(param2) clt.set_parameter(param3) param_list = clt.get_paramslist() self.assertEqual(3, len(param_list)) param_list = srv.get_paramslist() self.assertEqual(3, len(param_list)) if __name__ == '__main__': unittest.main()
0
apollo_public_repos/apollo/cyber/python/cyber_py3
apollo_public_repos/apollo/cyber/python/cyber_py3/test/init_test.py
#!/usr/bin/env python3 # **************************************************************************** # Copyright 2019 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # **************************************************************************** # -*- coding: utf-8 -*- """Module for test init.""" import unittest from cyber.python.cyber_py3 import cyber class TestInit(unittest.TestCase): """ Class for init unit test. """ def test_init(self): """ Test cyber. """ self.assertTrue(cyber.init()) self.assertTrue(cyber.ok()) cyber.shutdown() self.assertTrue(cyber.is_shutdown()) if __name__ == '__main__': unittest.main()
0
apollo_public_repos/apollo/cyber/python/cyber_py3
apollo_public_repos/apollo/cyber/python/cyber_py3/test/cyber_test.py
#!/usr/bin/env python3 # **************************************************************************** # Copyright 2019 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # **************************************************************************** # -*- coding: utf-8 -*- """Module for test cyber.""" import time import unittest from cyber.python.cyber_py3 import cyber from cyber.proto.simple_pb2 import SimpleMessage class TestCyber(unittest.TestCase): """ Class for node unit test. """ @staticmethod def callback(data): """ Reader callback. """ print("=" * 80) print("py:reader callback msg->:") print(data) print("=" * 80) def test_read_write(self): """ Unit test of reader. """ self.assertTrue(cyber.ok()) # Read. reader_node = cyber.Node("listener") reader = reader_node.create_reader("channel/chatter", SimpleMessage, self.callback) self.assertEqual(reader.name, "channel/chatter") self.assertEqual(reader.data_type, SimpleMessage) self.assertEqual(SimpleMessage.DESCRIPTOR.full_name, "apollo.cyber.proto.SimpleMessage") # Write. msg = SimpleMessage() msg.text = "talker:send Alex!" msg.integer = 0 self.assertTrue(cyber.ok()) writer_node = cyber.Node("writer") writer = writer_node.create_writer("channel/chatter", SimpleMessage, 7) self.assertEqual(writer.name, "channel/chatter") self.assertEqual( writer.data_type, "apollo.cyber.proto.SimpleMessage") self.assertTrue(writer.write(msg)) # Wait for data to be processed by callback function. time.sleep(0.1) if __name__ == '__main__': cyber.init() unittest.main() cyber.shutdown()
0
apollo_public_repos/apollo/cyber/python/cyber_py3
apollo_public_repos/apollo/cyber/python/cyber_py3/test/cyber_time_test.py
#!/usr/bin/env python3 # **************************************************************************** # Copyright 2019 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # **************************************************************************** # -*- coding: utf-8 -*- """Module for test cyber_time.""" import time import unittest from cyber.python.cyber_py3 import cyber from cyber.python.cyber_py3 import cyber_time class TestTime(unittest.TestCase): """ Class for node unit test. """ @classmethod def setUpClass(cls): cyber.init() @classmethod def tearDownClass(cls): cyber.shutdown() def test_time(self): ct = cyber_time.Time(123) self.assertEqual(123, ct.to_nsec()) ftime = ct.now().to_sec() print(ftime) time.sleep(1) ftime = cyber_time.Time.now().to_sec() print(ftime) ftime = cyber_time.Time.mono_time().to_sec() print(ftime) td1 = cyber_time.Duration(111) tm1 = ct - td1 self.assertEqual(12, tm1.to_nsec()) tm5 = cyber_time.Time(1.8) self.assertFalse(tm5.iszero()) self.assertEqual(1800000000, tm5.to_nsec()) tm7 = cyber_time.Time(tm5) self.assertEqual(1800000000, tm7.to_nsec()) def test_duration(self): td1 = cyber_time.Duration(111) td2 = cyber_time.Duration(601000000000) td3 = td2 - td1 self.assertEqual(111, td1.to_nsec()) self.assertEqual(601000000000, td2.to_nsec()) self.assertEqual(601000000000 - 111, td3.to_nsec()) print(td2.to_sec()) self.assertEqual(601.0, td2.to_sec()) self.assertFalse(td2.iszero()) print(str(td2)) td5 = cyber_time.Duration(1.8) td6 = td5 print(type(td6)) self.assertTrue(isinstance(td6, cyber_time.Duration)) def test_rate(self): rt1 = cyber_time.Rate(111) self.assertEqual(0, rt1.get_cycle_time().to_nsec()) self.assertEqual(111, rt1.get_expected_cycle_time().to_nsec()) rt2 = cyber_time.Rate(0.2) self.assertEqual(0, rt2.get_cycle_time().to_nsec()) self.assertEqual(5, rt2.get_expected_cycle_time().to_nsec()) rt3 = cyber_time.Rate(cyber_time.Duration(666)) self.assertEqual(0, rt3.get_cycle_time().to_nsec()) self.assertEqual(666, rt3.get_expected_cycle_time().to_nsec()) if __name__ == '__main__': unittest.main()
0
apollo_public_repos/apollo/cyber/python/cyber_py3
apollo_public_repos/apollo/cyber/python/cyber_py3/test/BUILD
load("@rules_python//python:defs.bzl", "py_test") py_test( name = "record_test", timeout = "short", srcs = ["record_test.py"], deps = [ "//cyber/proto:record_py_pb2", "//cyber/python/cyber_py3:record", "//cyber/proto:simple_py_pb2", ], ) py_test( name = "init_test", timeout = "short", srcs = ["init_test.py"], deps = [ "//cyber/python/cyber_py3:cyber", ], ) py_test( name = "cyber_test", timeout = "short", srcs = ["cyber_test.py"], deps = [ "//cyber/python/cyber_py3:cyber", "//cyber/proto:simple_py_pb2", ], ) # FIXME(all): parameter_test seems to run forever # py_test( # name = "parameter_test", # timeout = "short", # srcs = ["parameter_test.py"], # deps = [ # "//cyber/python/cyber_py3:cyber", # "//cyber/python/cyber_py3:parameter", # ], #) py_test( name = "cyber_time_test", timeout = "short", srcs = ["cyber_time_test.py"], deps = [ "//cyber/python/cyber_py3:cyber", "//cyber/python/cyber_py3:cyber_time", ], ) # FIXME(all): cyber_timer_test can't terminate # py_test( # name = "cyber_timer_test", # timeout = "short", # srcs = ["cyber_timer_test.py"], # deps = [ # "//cyber/python/cyber_py3:cyber", # "//cyber/python/cyber_py3:cyber_timer", # ], #)
0
apollo_public_repos/apollo/cyber/python/cyber_py3
apollo_public_repos/apollo/cyber/python/cyber_py3/test/cyber_timer_test.py
#!/usr/bin/env python3 # **************************************************************************** # Copyright 2019 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # **************************************************************************** """Module for test cyber timer.""" import time import unittest from cyber.python.cyber_py3 import cyber from cyber.python.cyber_py3 import cyber_timer class TestCyberTimer(unittest.TestCase): """ Class for cyber timer unit test. """ count = 0 @classmethod def setUpClass(cls): cyber.init() @classmethod def tearDownClass(cls): cyber.shutdown() def func(cls): print('Callback function is called [%d] times.' % cls.count) cls.count += 1 def test_timer(self): ct = cyber_timer.Timer(100, self.func, 0) # 100ms ct.start() time.sleep(1) # 1s ct.stop() print('+' * 40 + 'test set_option' + '+' * 40) ct2 = cyber_timer.Timer() # 10ms ct2.set_option(100, self.func, 0) ct2.start() time.sleep(1) # 1s ct2.stop() if __name__ == '__main__': unittest.main() # TODO(xiaoxq): It crashes here.
0
apollo_public_repos/apollo/cyber/python/cyber_py3
apollo_public_repos/apollo/cyber/python/cyber_py3/examples/talker.py
#!/usr/bin/env python3 # **************************************************************************** # Copyright 2019 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # **************************************************************************** # -*- coding: utf-8 -*- """Module for example of talker.""" import time from cyber.python.cyber_py3 import cyber from cyber.proto.unit_test_pb2 import ChatterBenchmark def test_talker_class(): """ Test talker. """ msg = ChatterBenchmark() msg.content = "py:talker:send Alex!" msg.stamp = 9999 msg.seq = 0 print(msg) test_node = cyber.Node("node_name1") g_count = 1 writer = test_node.create_writer("channel/chatter", ChatterBenchmark, 6) while not cyber.is_shutdown(): time.sleep(1) g_count = g_count + 1 msg.seq = g_count msg.content = "I am python talker." print("=" * 80) print("write msg -> %s" % msg) writer.write(msg) if __name__ == '__main__': cyber.init("talker_sample") test_talker_class() cyber.shutdown()
0
apollo_public_repos/apollo/cyber/python/cyber_py3
apollo_public_repos/apollo/cyber/python/cyber_py3/examples/time.py
#!/usr/bin/env python3 # **************************************************************************** # Copyright 2019 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # **************************************************************************** # -*- coding: utf-8 -*- """Module for example of cyber time.""" import time from cyber.python.cyber_py3 import cyber_time def test_time(): ct = cyber_time.Time(123) print(ct.to_nsec()) ftime = ct.now().to_sec() print(ftime) time.sleep(1) ftime = cyber_time.Time.now().to_sec() print(ftime) ftime = cyber_time.Time.mono_time().to_sec() print(ftime) td1 = cyber_time.Duration(111) tm1 = ct - td1 print("ct sub du is ", tm1) tm1 = ct - td1 print(tm1) tm5 = cyber_time.Time(1.8) tm7 = cyber_time.Time(tm5) print(tm7) def test_duration(): td1 = cyber_time.Duration(111) td2 = cyber_time.Duration(601000000000) td3 = td2 - td1 print(td1, td1.to_nsec()) print(td2, td2.to_nsec()) print(td3, td3.to_nsec()) print(td2.to_sec()) print(td2.iszero()) print(str(td2)) td5 = cyber_time.Duration(1.8) td6 = td5 print(type(td6)) td7 = cyber_time.Duration(td6) print(td7) # td7 = cyber_time.Duration("zzz") # print(td7) # print(type(td2)) def test_rate(): rt1 = cyber_time.Rate(111) rt2 = cyber_time.Rate(0.2) rt3 = cyber_time.Rate(cyber_time.Duration(666)) print(rt1) print(rt2) print(rt3) if __name__ == '__main__': print("test time", "-" * 50) test_time() print("test duration", "-" * 50) test_duration() print("test rate", "-" * 50) test_rate()
0
apollo_public_repos/apollo/cyber/python/cyber_py3
apollo_public_repos/apollo/cyber/python/cyber_py3/examples/service.py
#!/usr/bin/env python3 # **************************************************************************** # Copyright 2019 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # **************************************************************************** # -*- coding: utf-8 -*- """Module for example of listener.""" from cyber.python.cyber_py3 import cyber from cyber.proto.unit_test_pb2 import ChatterBenchmark def callback(data): print("-" * 80) print("get Request [ ", data, " ]") return ChatterBenchmark(content="svr: Hello client!", seq=data.seq + 2) def test_service_class(): """ Reader message. """ print("=" * 120) node = cyber.Node("service_node") r = node.create_service( "server_01", ChatterBenchmark, ChatterBenchmark, callback) node.spin() if __name__ == '__main__': cyber.init() test_service_class() cyber.shutdown()
0
apollo_public_repos/apollo/cyber/python/cyber_py3
apollo_public_repos/apollo/cyber/python/cyber_py3/examples/record_channel_info.py
#!/usr/bin/env python3 # **************************************************************************** # Copyright 2019 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # **************************************************************************** # -*- coding: utf-8 -*- """Module for example of record.""" import sys from cyber.python.cyber_py3 import cyber from cyber.python.cyber_py3 import record from cyber.proto import record_pb2 def print_channel_info(file_path): freader = record.RecordReader(file_path) channels = freader.get_channellist() header_msg = freader.get_headerstring() header = record_pb2.Header() header.ParseFromString(header_msg) print('\n++++++++++++Begin Channel Info Statistics++++++++++++++') print('-' * 40) print( 'record version: [%d:%d]' % (header.major_version, header.minor_version)) print('record message_number: %s' % str(header.message_number)) print('record file size(Byte): %s' % str(header.size)) print('chunk_number: %d' % header.chunk_number) print('channel count: %d' % len(channels)) print('-' * 40) count = 0 for channel in channels: desc = freader.get_protodesc(channel) count += 1 print( 'Channel: %s, count: %d, desc size: %d' % (channel, count, len(desc))) # print(desc) print("++++++++++++Finish Channel Info Statistics++++++++++++++\n") if __name__ == '__main__': if len(sys.argv) < 2: print('Usage: %s record_file' % sys.argv[0]) sys.exit(0) cyber.init() print_channel_info(sys.argv[1]) cyber.shutdown()
0
apollo_public_repos/apollo/cyber/python/cyber_py3
apollo_public_repos/apollo/cyber/python/cyber_py3/examples/timer.py
#!/usr/bin/env python3 # **************************************************************************** # Copyright 2019 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # **************************************************************************** """Module for example of timer.""" import time from cyber.python.cyber_py3 import cyber from cyber.python.cyber_py3 import cyber_timer count = 0 def fun(): global count print("cb fun is called:", count) count += 1 def test_timer(): cyber.init() ct = cyber_timer.Timer(10, fun, 0) # 10ms ct.start() time.sleep(1) # 1s ct.stop() print("+" * 80, "test set_option") ct2 = cyber_timer.Timer() # 10ms ct2.set_option(10, fun, 0) ct2.start() time.sleep(1) # 1s ct2.stop() cyber.shutdown() if __name__ == '__main__': test_timer()
0
apollo_public_repos/apollo/cyber/python/cyber_py3
apollo_public_repos/apollo/cyber/python/cyber_py3/examples/client.py
#!/usr/bin/env python3 # **************************************************************************** # Copyright 2019 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # **************************************************************************** # -*- coding: utf-8 -*- """Module for example of listener.""" import time from cyber.python.cyber_py3 import cyber from cyber.proto.unit_test_pb2 import ChatterBenchmark def test_client_class(): """ Client send request """ node = cyber.Node("client_node") client = node.create_client("server_01", ChatterBenchmark, ChatterBenchmark) req = ChatterBenchmark() req.content = "clt:Hello service!" req.seq = 0 count = 0 while not cyber.is_shutdown(): time.sleep(1) count += 1 req.seq = count print("-" * 80) response = client.send_request(req) print("get Response [ ", response, " ]") if __name__ == '__main__': cyber.init() test_client_class() cyber.shutdown()
0
apollo_public_repos/apollo/cyber/python/cyber_py3
apollo_public_repos/apollo/cyber/python/cyber_py3/examples/record.py
#!/usr/bin/env python3 # **************************************************************************** # Copyright 2019 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # **************************************************************************** # -*- coding: utf-8 -*- """ Module for example of record. Run with: bazel run //cyber/python/cyber_py3/examples:record """ import time from google.protobuf.descriptor_pb2 import FileDescriptorProto from cyber.proto.unit_test_pb2 import Chatter from cyber.python.cyber_py3 import record from modules.common.util.testdata.simple_pb2 import SimpleMessage MSG_TYPE = "apollo.common.util.test.SimpleMessage" MSG_TYPE_CHATTER = "apollo.cyber.proto.Chatter" def test_record_writer(writer_path): """ Record writer. """ fwriter = record.RecordWriter() fwriter.set_size_fileseg(0) fwriter.set_intervaltime_fileseg(0) if not fwriter.open(writer_path): print('Failed to open record writer!') return print('+++ Begin to writer +++') # Writer 2 SimpleMessage msg = SimpleMessage() msg.text = "AAAAAA" file_desc = msg.DESCRIPTOR.file proto = FileDescriptorProto() file_desc.CopyToProto(proto) proto.name = file_desc.name desc_str = proto.SerializeToString() print(msg.DESCRIPTOR.full_name) fwriter.write_channel( 'simplemsg_channel', msg.DESCRIPTOR.full_name, desc_str) fwriter.write_message('simplemsg_channel', msg, 990, False) fwriter.write_message('simplemsg_channel', msg.SerializeToString(), 991) # Writer 2 Chatter msg = Chatter() msg.timestamp = 99999 msg.lidar_timestamp = 100 msg.seq = 1 file_desc = msg.DESCRIPTOR.file proto = FileDescriptorProto() file_desc.CopyToProto(proto) proto.name = file_desc.name desc_str = proto.SerializeToString() print(msg.DESCRIPTOR.full_name) fwriter.write_channel('chatter_a', msg.DESCRIPTOR.full_name, desc_str) fwriter.write_message('chatter_a', msg, 992, False) msg.seq = 2 fwriter.write_message("chatter_a", msg.SerializeToString(), 993) fwriter.close() def test_record_reader(reader_path): """ Record reader. """ freader = record.RecordReader(reader_path) time.sleep(1) print('+' * 80) print('+++ Begin to read +++') count = 0 for channel_name, msg, datatype, timestamp in freader.read_messages(): count += 1 print('=' * 80) print('read [%d] messages' % count) print('channel_name -> %s' % channel_name) print('msgtime -> %d' % timestamp) print('msgnum -> %d' % freader.get_messagenumber(channel_name)) print('msgtype -> %s' % datatype) print('message is -> %s' % msg) print('***After parse(if needed),the message is ->') if datatype == MSG_TYPE: msg_new = SimpleMessage() msg_new.ParseFromString(msg) print(msg_new) elif datatype == MSG_TYPE_CHATTER: msg_new = Chatter() msg_new.ParseFromString(msg) print(msg_new) if __name__ == '__main__': test_record_file = "/tmp/test_writer.record" print('Begin to write record file: {}'.format(test_record_file)) test_record_writer(test_record_file) print('Begin to read record file: {}'.format(test_record_file)) test_record_reader(test_record_file)
0
apollo_public_repos/apollo/cyber/python/cyber_py3
apollo_public_repos/apollo/cyber/python/cyber_py3/examples/BUILD
load("@rules_python//python:defs.bzl", "py_binary") package(default_visibility = ["//visibility:public"]) py_binary( name = "record", srcs = ["record.py"], deps = [ "//cyber/proto:unit_test_py_pb2", "//cyber/python/cyber_py3:record", "//modules/common_msgs/basic_msgs:error_code_py_pb2", "//modules/common_msgs/basic_msgs:header_py_pb2", "//modules/common/util/testdata:simple_py_pb2", ], ) py_binary( name = "time", srcs = ["time.py"], deps = [ "//cyber/python/cyber_py3:cyber_time", ], ) py_binary( name = "timer", srcs = ["timer.py"], deps = [ "//cyber/python/cyber_py3:cyber", "//cyber/python/cyber_py3:cyber_timer", ], ) py_binary( name = "talker", srcs = ["talker.py"], deps = [ "//cyber/proto:unit_test_py_pb2", "//cyber/python/cyber_py3:cyber", ], ) py_binary( name = "listener", srcs = ["listener.py"], deps = [ "//cyber/proto:unit_test_py_pb2", "//cyber/python/cyber_py3:cyber", ], ) py_binary( name = "parameter", srcs = ["parameter.py"], deps = [ "//cyber/python/cyber_py3:cyber", "//cyber/python/cyber_py3:parameter", ], ) py_binary( name = "service", srcs = ["service.py"], deps = [ "//cyber/proto:unit_test_py_pb2", "//cyber/python/cyber_py3:cyber", ], ) py_binary( name = "client", srcs = ["client.py"], deps = [ "//cyber/proto:unit_test_py_pb2", "//cyber/python/cyber_py3:cyber", ], ) py_binary( name = "record_trans", srcs = ["record_trans.py"], deps = [ "//cyber/python/cyber_py3:cyber", "//cyber/python/cyber_py3:record", ], ) py_binary( name = "record_channel_info", srcs = ["record_channel_info.py"], deps = [ "//cyber/proto:record_py_pb2", "//cyber/python/cyber_py3:cyber", "//cyber/python/cyber_py3:record", ], )
0
apollo_public_repos/apollo/cyber/python/cyber_py3
apollo_public_repos/apollo/cyber/python/cyber_py3/examples/record_trans.py
#!/usr/bin/env python3 # **************************************************************************** # Copyright 2019 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # **************************************************************************** # -*- coding: utf-8 -*- """Module for example of record trans.""" import sys from cyber.python.cyber_py3 import cyber from cyber.python.cyber_py3 import record TEST_RECORD_FILE = "trans_ret.record" def test_record_trans(reader_path): """ Record trans. """ fwriter = record.RecordWriter() if not fwriter.open(TEST_RECORD_FILE): print('Failed to open record writer!') return print('+++ Begin to trans +++') fread = record.RecordReader(reader_path) count = 0 for channelname, msg, datatype, timestamp in fread.read_messages(): # print channelname, timestamp, fread.get_messagenumber(channelname) desc = fread.get_protodesc(channelname) fwriter.write_channel(channelname, datatype, desc) fwriter.write_message(channelname, msg, timestamp) count += 1 print('-' * 80) print('Message count: %d' % count) print('Channel info: ') channel_list = fread.get_channellist() print('Channel count: %d' % len(channel_list)) print(channel_list) if __name__ == '__main__': if len(sys.argv) < 2: print('Usage: %s record_file' % sys.argv[0]) sys.exit(0) cyber.init() test_record_trans(sys.argv[1]) cyber.shutdown()
0
apollo_public_repos/apollo/cyber/python/cyber_py3
apollo_public_repos/apollo/cyber/python/cyber_py3/examples/parameter.py
#!/usr/bin/env python3 # **************************************************************************** # Copyright 2019 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # **************************************************************************** # -*- coding: utf-8 -*- """Module for example of parameter.""" from cyber.python.cyber_py3 import cyber from cyber.python.cyber_py3 import parameter PARAM_SERVICE_NAME = "global_parameter_service" def print_param_srv(): param1 = parameter.Parameter("author_name", "WanderingEarth") param2 = parameter.Parameter("author_age", 5000) param3 = parameter.Parameter("author_score", 888.88) test_node = cyber.Node(PARAM_SERVICE_NAME) srv = parameter.ParameterServer(test_node) node_handle = cyber.Node("service_client_node") clt = parameter.ParameterClient(test_node, PARAM_SERVICE_NAME) clt.set_parameter(param1) clt.set_parameter(param2) clt.set_parameter(param3) param_list = clt.get_paramslist() print("clt param lst len is ", len(param_list)) for param in param_list: print(param.debug_string()) print("") param_list = srv.get_paramslist() print("srv param lst len is ", len(param_list)) for param in param_list: print(param.debug_string()) if __name__ == '__main__': cyber.init() print_param_srv() cyber.shutdown()
0
apollo_public_repos/apollo/cyber/python/cyber_py3
apollo_public_repos/apollo/cyber/python/cyber_py3/examples/listener.py
#!/usr/bin/env python3 # **************************************************************************** # Copyright 2019 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # **************************************************************************** # -*- coding: utf-8 -*- """Module for example of listener.""" from cyber.python.cyber_py3 import cyber from cyber.proto.unit_test_pb2 import ChatterBenchmark def callback(data): """ Reader message callback. """ print("=" * 80) print("py:reader callback msg->:") print(data) print("=" * 80) def test_listener_class(): """ Reader message. """ print("=" * 120) test_node = cyber.Node("listener") test_node.create_reader("channel/chatter", ChatterBenchmark, callback) test_node.spin() if __name__ == '__main__': cyber.init() test_listener_class() cyber.shutdown()
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/timer/timer_bucket.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef CYBER_TIMER_TIMER_BUCKET_H_ #define CYBER_TIMER_TIMER_BUCKET_H_ #include <list> #include <memory> #include <mutex> #include "cyber/timer/timer_task.h" namespace apollo { namespace cyber { class TimerBucket { public: void AddTask(const std::shared_ptr<TimerTask>& task) { std::lock_guard<std::mutex> lock(mutex_); task_list_.push_back(task); } std::mutex& mutex() { return mutex_; } std::list<std::weak_ptr<TimerTask>>& task_list() { return task_list_; } private: std::mutex mutex_; std::list<std::weak_ptr<TimerTask>> task_list_; }; } // namespace cyber } // namespace apollo #endif // CYBER_TIMER_TIMER_BUCKET_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/timer/timer.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef CYBER_TIMER_TIMER_H_ #define CYBER_TIMER_TIMER_H_ #include <atomic> #include <memory> #include "cyber/timer/timing_wheel.h" namespace apollo { namespace cyber { /** * @brief The options of timer * */ struct TimerOption { /** * @brief Construct a new Timer Option object * * @param period The period of the timer, unit is ms * @param callback The task that the timer needs to perform * @param oneshot Oneshot or period */ TimerOption(uint32_t period, std::function<void()> callback, bool oneshot) : period(period), callback(callback), oneshot(oneshot) {} /** * @brief Default constructor for initializer list * */ TimerOption() : period(), callback(), oneshot() {} /** * @brief The period of the timer, unit is ms * max: 512 * 64 * min: 1 */ uint32_t period = 0; /**The task that the timer needs to perform*/ std::function<void()> callback; /** * True: perform the callback only after the first timing cycle * False: perform the callback every timed period */ bool oneshot; }; /** * @class Timer * @brief Used to perform oneshot or periodic timing tasks * */ class Timer { public: Timer(); /** * @brief Construct a new Timer object * * @param opt Timer option */ explicit Timer(TimerOption opt); /** * @brief Construct a new Timer object * * @param period The period of the timer, unit is ms * @param callback The tasks that the timer needs to perform * @param oneshot True: perform the callback only after the first timing cycle * False: perform the callback every timed period */ Timer(uint32_t period, std::function<void()> callback, bool oneshot); ~Timer(); /** * @brief Set the Timer Option object * * @param opt The timer option will be set */ void SetTimerOption(TimerOption opt); /** * @brief Start the timer * */ void Start(); /** * @brief Stop the timer * */ void Stop(); private: bool InitTimerTask(); uint64_t timer_id_; TimerOption timer_opt_; TimingWheel* timing_wheel_ = nullptr; std::shared_ptr<TimerTask> task_; std::atomic<bool> started_ = {false}; }; } // namespace cyber } // namespace apollo #endif // CYBER_TIMER_TIMER_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/timer/timer_test.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /* note that the frame code of the following is Generated by script */ #include "cyber/timer/timer.h" #include <memory> #include <utility> #include "gtest/gtest.h" #include "cyber/common/util.h" #include "cyber/cyber.h" #include "cyber/init.h" namespace apollo { namespace cyber { namespace timer { using cyber::Timer; using cyber::TimerOption; TEST(TimerTest, one_shot) { int count = 0; Timer timer( 100, [&count] { count = 100; }, true); timer.Start(); std::this_thread::sleep_for(std::chrono::milliseconds(90)); EXPECT_EQ(0, count); // Here we need to consider the scheduling delay, up to 500ms, make sure the // unit test passes. std::this_thread::sleep_for(std::chrono::milliseconds(500)); EXPECT_EQ(100, count); timer.Stop(); } TEST(TimerTest, cycle) { using TimerPtr = std::shared_ptr<Timer>; int count = 0; TimerPtr timers[1000]; TimerOption opt; opt.oneshot = false; opt.callback = [=] { AINFO << count; }; for (int i = 0; i < 1000; i++) { opt.period = i + 1; timers[i] = std::make_shared<Timer>(); timers[i]->SetTimerOption(opt); timers[i]->Start(); } std::this_thread::sleep_for(std::chrono::seconds(3)); for (int i = 0; i < 1000; i++) { timers[i]->Stop(); } } TEST(TimerTest, start_stop) { int count = 0; Timer timer( 2, [count] { AINFO << count; }, false); for (int i = 0; i < 100; i++) { timer.Start(); std::this_thread::sleep_for(std::chrono::milliseconds(10)); timer.Stop(); } } TEST(TimerTest, sim_mode) { auto count = 0; auto func = [count]() { AINFO << count; }; TimerOption to{1000, func, false}; { Timer t; t.SetTimerOption(to); common::GlobalData::Instance()->EnableSimulationMode(); t.Start(); common::GlobalData::Instance()->DisableSimulationMode(); t.Start(); t.Start(); } } } // namespace timer } // namespace cyber } // namespace apollo int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); apollo::cyber::Init(argv[0]); return RUN_ALL_TESTS(); }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/timer/timer.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/timer/timer.h" #include <cmath> #include "cyber/common/global_data.h" namespace apollo { namespace cyber { namespace { std::atomic<uint64_t> global_timer_id = {0}; uint64_t GenerateTimerId() { return global_timer_id.fetch_add(1); } } // namespace Timer::Timer() { timing_wheel_ = TimingWheel::Instance(); timer_id_ = GenerateTimerId(); } Timer::Timer(TimerOption opt) : timer_opt_(opt) { timing_wheel_ = TimingWheel::Instance(); timer_id_ = GenerateTimerId(); } Timer::Timer(uint32_t period, std::function<void()> callback, bool oneshot) { timing_wheel_ = TimingWheel::Instance(); timer_id_ = GenerateTimerId(); timer_opt_.period = period; timer_opt_.callback = callback; timer_opt_.oneshot = oneshot; } void Timer::SetTimerOption(TimerOption opt) { timer_opt_ = opt; } bool Timer::InitTimerTask() { if (timer_opt_.period == 0) { AERROR << "Max interval must great than 0"; return false; } if (timer_opt_.period >= TIMER_MAX_INTERVAL_MS) { AERROR << "Max interval must less than " << TIMER_MAX_INTERVAL_MS; return false; } task_.reset(new TimerTask(timer_id_)); task_->interval_ms = timer_opt_.period; task_->next_fire_duration_ms = task_->interval_ms; if (timer_opt_.oneshot) { std::weak_ptr<TimerTask> task_weak_ptr = task_; task_->callback = [callback = this->timer_opt_.callback, task_weak_ptr]() { auto task = task_weak_ptr.lock(); if (task) { std::lock_guard<std::mutex> lg(task->mutex); callback(); } }; } else { std::weak_ptr<TimerTask> task_weak_ptr = task_; task_->callback = [callback = this->timer_opt_.callback, task_weak_ptr]() { auto task = task_weak_ptr.lock(); if (!task) { return; } std::lock_guard<std::mutex> lg(task->mutex); auto start = Time::MonoTime().ToNanosecond(); callback(); auto end = Time::MonoTime().ToNanosecond(); uint64_t execute_time_ns = end - start; uint64_t execute_time_ms = #if defined(__aarch64__) ::llround(static_cast<double>(execute_time_ns) / 1e6); #else std::llround(static_cast<double>(execute_time_ns) / 1e6); #endif if (task->last_execute_time_ns == 0) { task->last_execute_time_ns = start; } else { task->accumulated_error_ns += start - task->last_execute_time_ns - task->interval_ms * 1000000; } ADEBUG << "start: " << start << "\t last: " << task->last_execute_time_ns << "\t execut time:" << execute_time_ms << "\t accumulated_error_ns: " << task->accumulated_error_ns; task->last_execute_time_ns = start; if (execute_time_ms >= task->interval_ms) { task->next_fire_duration_ms = TIMER_RESOLUTION_MS; } else { #if defined(__aarch64__) int64_t accumulated_error_ms = ::llround( #else int64_t accumulated_error_ms = std::llround( #endif static_cast<double>(task->accumulated_error_ns) / 1e6); if (static_cast<int64_t>(task->interval_ms - execute_time_ms - TIMER_RESOLUTION_MS) >= accumulated_error_ms) { task->next_fire_duration_ms = task->interval_ms - execute_time_ms - accumulated_error_ms; } else { task->next_fire_duration_ms = TIMER_RESOLUTION_MS; } ADEBUG << "error ms: " << accumulated_error_ms << " execute time: " << execute_time_ms << " next fire: " << task->next_fire_duration_ms << " error ns: " << task->accumulated_error_ns; } TimingWheel::Instance()->AddTask(task); }; } return true; } void Timer::Start() { if (!common::GlobalData::Instance()->IsRealityMode()) { return; } if (!started_.exchange(true)) { if (InitTimerTask()) { timing_wheel_->AddTask(task_); AINFO << "start timer [" << task_->timer_id_ << "]"; } } } void Timer::Stop() { if (started_.exchange(false) && task_) { AINFO << "stop timer, the timer_id: " << timer_id_; // using a shared pointer to hold task_->mutex before task_ reset auto tmp_task = task_; { std::lock_guard<std::mutex> lg(tmp_task->mutex); task_.reset(); } } } Timer::~Timer() { if (task_) { Stop(); } } } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/timer/timer_task.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef CYBER_TIMER_TIMER_TASK_H_ #define CYBER_TIMER_TIMER_TASK_H_ #include <functional> #include <mutex> namespace apollo { namespace cyber { class TimerBucket; struct TimerTask { explicit TimerTask(uint64_t timer_id) : timer_id_(timer_id) {} uint64_t timer_id_ = 0; std::function<void()> callback; uint64_t interval_ms = 0; uint64_t remainder_interval_ms = 0; uint64_t next_fire_duration_ms = 0; int64_t accumulated_error_ns = 0; uint64_t last_execute_time_ns = 0; std::mutex mutex; }; } // namespace cyber } // namespace apollo #endif // CYBER_TIMER_TIMER_TASK_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/timer/timing_wheel.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef CYBER_TIMER_TIMING_WHEEL_H_ #define CYBER_TIMER_TIMING_WHEEL_H_ #include <future> #include <list> #include <memory> #include <thread> #include "cyber/common/log.h" #include "cyber/common/macros.h" #include "cyber/scheduler/scheduler_factory.h" #include "cyber/time/rate.h" #include "cyber/timer/timer_bucket.h" namespace apollo { namespace cyber { struct TimerTask; static const uint64_t WORK_WHEEL_SIZE = 512; static const uint64_t ASSISTANT_WHEEL_SIZE = 64; static const uint64_t TIMER_RESOLUTION_MS = 2; static const uint64_t TIMER_MAX_INTERVAL_MS = WORK_WHEEL_SIZE * ASSISTANT_WHEEL_SIZE * TIMER_RESOLUTION_MS; class TimingWheel { public: ~TimingWheel() { if (running_) { Shutdown(); } } void Start(); void Shutdown(); void Tick(); void AddTask(const std::shared_ptr<TimerTask>& task); void AddTask(const std::shared_ptr<TimerTask>& task, const uint64_t current_work_wheel_index); void Cascade(const uint64_t assistant_wheel_index); void TickFunc(); inline uint64_t TickCount() const { return tick_count_; } private: inline uint64_t GetWorkWheelIndex(const uint64_t index) { return index & (WORK_WHEEL_SIZE - 1); } inline uint64_t GetAssistantWheelIndex(const uint64_t index) { return index & (ASSISTANT_WHEEL_SIZE - 1); } bool running_ = false; uint64_t tick_count_ = 0; std::mutex running_mutex_; TimerBucket work_wheel_[WORK_WHEEL_SIZE]; TimerBucket assistant_wheel_[ASSISTANT_WHEEL_SIZE]; uint64_t current_work_wheel_index_ = 0; std::mutex current_work_wheel_index_mutex_; uint64_t current_assistant_wheel_index_ = 0; std::mutex current_assistant_wheel_index_mutex_; std::thread tick_thread_; DECLARE_SINGLETON(TimingWheel) }; } // namespace cyber } // namespace apollo #endif // CYBER_TIMER_TIMING_WHEEL_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/timer/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) filegroup( name = "cyber_timer_hdrs", srcs = glob([ "*.h", ]), ) cc_library( name = "timer", srcs = ["timer.cc"], hdrs = ["timer.h"], deps = [ ":timing_wheel", "//cyber/common:global_data", ], ) cc_library( name = "timer_task", hdrs = ["timer_task.h"], ) cc_library( name = "timer_bucket", hdrs = ["timer_bucket.h"], deps = [ ":timer_task", ], ) cc_library( name = "timing_wheel", srcs = ["timing_wheel.cc"], hdrs = ["timing_wheel.h"], deps = [ ":timer_bucket", "//cyber/task", "//cyber/time", "//cyber/time:duration", "//cyber/time:rate", ], ) cc_test( name = "timer_test", size = "small", srcs = ["timer_test.cc"], deps = [ "//cyber:cyber_core", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cpplint()
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/timer/timing_wheel.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/timer/timing_wheel.h" #include <cmath> #include "cyber/task/task.h" namespace apollo { namespace cyber { void TimingWheel::Start() { std::lock_guard<std::mutex> lock(running_mutex_); if (!running_) { ADEBUG << "TimeWheel start ok"; running_ = true; tick_thread_ = std::thread([this]() { this->TickFunc(); }); scheduler::Instance()->SetInnerThreadAttr("timer", &tick_thread_); } } void TimingWheel::Shutdown() { std::lock_guard<std::mutex> lock(running_mutex_); if (running_) { running_ = false; if (tick_thread_.joinable()) { tick_thread_.join(); } } } void TimingWheel::Tick() { auto& bucket = work_wheel_[current_work_wheel_index_]; { std::lock_guard<std::mutex> lock(bucket.mutex()); auto ite = bucket.task_list().begin(); while (ite != bucket.task_list().end()) { auto task = ite->lock(); if (task) { ADEBUG << "index: " << current_work_wheel_index_ << " timer id: " << task->timer_id_; auto* callback = reinterpret_cast<std::function<void()>*>(&(task->callback)); cyber::Async([this, callback] { if (this->running_) { (*callback)(); } }); } ite = bucket.task_list().erase(ite); } } } void TimingWheel::AddTask(const std::shared_ptr<TimerTask>& task) { AddTask(task, current_work_wheel_index_); } void TimingWheel::AddTask(const std::shared_ptr<TimerTask>& task, const uint64_t current_work_wheel_index) { if (!running_) { Start(); } auto work_wheel_index = current_work_wheel_index + static_cast<uint64_t>(std::ceil( static_cast<double>(task->next_fire_duration_ms) / TIMER_RESOLUTION_MS)); if (work_wheel_index >= WORK_WHEEL_SIZE) { auto real_work_wheel_index = GetWorkWheelIndex(work_wheel_index); task->remainder_interval_ms = real_work_wheel_index; auto assistant_ticks = work_wheel_index / WORK_WHEEL_SIZE; if (assistant_ticks == 1 && real_work_wheel_index < current_work_wheel_index_) { work_wheel_[real_work_wheel_index].AddTask(task); ADEBUG << "add task to work wheel. index :" << real_work_wheel_index; } else { auto assistant_wheel_index = 0; { std::lock_guard<std::mutex> lock(current_assistant_wheel_index_mutex_); assistant_wheel_index = GetAssistantWheelIndex( current_assistant_wheel_index_ + assistant_ticks); assistant_wheel_[assistant_wheel_index].AddTask(task); } ADEBUG << "add task to assistant wheel. index : " << assistant_wheel_index; } } else { work_wheel_[work_wheel_index].AddTask(task); ADEBUG << "add task [" << task->timer_id_ << "] to work wheel. index :" << work_wheel_index; } } void TimingWheel::Cascade(const uint64_t assistant_wheel_index) { auto& bucket = assistant_wheel_[assistant_wheel_index]; std::lock_guard<std::mutex> lock(bucket.mutex()); auto ite = bucket.task_list().begin(); while (ite != bucket.task_list().end()) { auto task = ite->lock(); if (task) { work_wheel_[task->remainder_interval_ms].AddTask(task); } ite = bucket.task_list().erase(ite); } } void TimingWheel::TickFunc() { Rate rate(TIMER_RESOLUTION_MS * 1000000); // ms to ns while (running_) { Tick(); // AINFO_EVERY(1000) << "Tick " << TickCount(); tick_count_++; rate.Sleep(); { std::lock_guard<std::mutex> lock(current_work_wheel_index_mutex_); current_work_wheel_index_ = GetWorkWheelIndex(current_work_wheel_index_ + 1); } if (current_work_wheel_index_ == 0) { { std::lock_guard<std::mutex> lock(current_assistant_wheel_index_mutex_); current_assistant_wheel_index_ = GetAssistantWheelIndex(current_assistant_wheel_index_ + 1); } Cascade(current_assistant_wheel_index_); } } } TimingWheel::TimingWheel() {} } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/blocker/blocker.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef CYBER_BLOCKER_BLOCKER_H_ #define CYBER_BLOCKER_BLOCKER_H_ #include <cstddef> #include <functional> #include <list> #include <memory> #include <mutex> #include <string> #include <unordered_map> #include <vector> namespace apollo { namespace cyber { namespace blocker { class BlockerBase { public: virtual ~BlockerBase() = default; virtual void Reset() = 0; virtual void ClearObserved() = 0; virtual void ClearPublished() = 0; virtual void Observe() = 0; virtual bool IsObservedEmpty() const = 0; virtual bool IsPublishedEmpty() const = 0; virtual bool Unsubscribe(const std::string& callback_id) = 0; virtual size_t capacity() const = 0; virtual void set_capacity(size_t capacity) = 0; virtual const std::string& channel_name() const = 0; }; struct BlockerAttr { BlockerAttr() : capacity(10), channel_name("") {} explicit BlockerAttr(const std::string& channel) : capacity(10), channel_name(channel) {} BlockerAttr(size_t cap, const std::string& channel) : capacity(cap), channel_name(channel) {} BlockerAttr(const BlockerAttr& attr) : capacity(attr.capacity), channel_name(attr.channel_name) {} size_t capacity; std::string channel_name; }; template <typename T> class Blocker : public BlockerBase { friend class BlockerManager; public: using MessageType = T; using MessagePtr = std::shared_ptr<T>; using MessageQueue = std::list<MessagePtr>; using Callback = std::function<void(const MessagePtr&)>; using CallbackMap = std::unordered_map<std::string, Callback>; using Iterator = typename std::list<std::shared_ptr<T>>::const_iterator; explicit Blocker(const BlockerAttr& attr); virtual ~Blocker(); void Publish(const MessageType& msg); void Publish(const MessagePtr& msg); void ClearObserved() override; void ClearPublished() override; void Observe() override; bool IsObservedEmpty() const override; bool IsPublishedEmpty() const override; bool Subscribe(const std::string& callback_id, const Callback& callback); bool Unsubscribe(const std::string& callback_id) override; const MessageType& GetLatestObserved() const; const MessagePtr GetLatestObservedPtr() const; const MessagePtr GetOldestObservedPtr() const; const MessagePtr GetLatestPublishedPtr() const; Iterator ObservedBegin() const; Iterator ObservedEnd() const; size_t capacity() const override; void set_capacity(size_t capacity) override; const std::string& channel_name() const override; private: void Reset() override; void Enqueue(const MessagePtr& msg); void Notify(const MessagePtr& msg); BlockerAttr attr_; MessageQueue observed_msg_queue_; MessageQueue published_msg_queue_; mutable std::mutex msg_mutex_; CallbackMap published_callbacks_; mutable std::mutex cb_mutex_; MessageType dummy_msg_; }; template <typename T> Blocker<T>::Blocker(const BlockerAttr& attr) : attr_(attr), dummy_msg_() {} template <typename T> Blocker<T>::~Blocker() { published_msg_queue_.clear(); observed_msg_queue_.clear(); published_callbacks_.clear(); } template <typename T> void Blocker<T>::Publish(const MessageType& msg) { Publish(std::make_shared<MessageType>(msg)); } template <typename T> void Blocker<T>::Publish(const MessagePtr& msg) { Enqueue(msg); Notify(msg); } template <typename T> void Blocker<T>::Reset() { { std::lock_guard<std::mutex> lock(msg_mutex_); observed_msg_queue_.clear(); published_msg_queue_.clear(); } { std::lock_guard<std::mutex> lock(cb_mutex_); published_callbacks_.clear(); } } template <typename T> void Blocker<T>::ClearObserved() { std::lock_guard<std::mutex> lock(msg_mutex_); observed_msg_queue_.clear(); } template <typename T> void Blocker<T>::ClearPublished() { std::lock_guard<std::mutex> lock(msg_mutex_); published_msg_queue_.clear(); } template <typename T> void Blocker<T>::Observe() { std::lock_guard<std::mutex> lock(msg_mutex_); observed_msg_queue_ = published_msg_queue_; } template <typename T> bool Blocker<T>::IsObservedEmpty() const { std::lock_guard<std::mutex> lock(msg_mutex_); return observed_msg_queue_.empty(); } template <typename T> bool Blocker<T>::IsPublishedEmpty() const { std::lock_guard<std::mutex> lock(msg_mutex_); return published_msg_queue_.empty(); } template <typename T> bool Blocker<T>::Subscribe(const std::string& callback_id, const Callback& callback) { std::lock_guard<std::mutex> lock(cb_mutex_); if (published_callbacks_.find(callback_id) != published_callbacks_.end()) { return false; } published_callbacks_[callback_id] = callback; return true; } template <typename T> bool Blocker<T>::Unsubscribe(const std::string& callback_id) { std::lock_guard<std::mutex> lock(cb_mutex_); return published_callbacks_.erase(callback_id) != 0; } template <typename T> auto Blocker<T>::GetLatestObserved() const -> const MessageType& { std::lock_guard<std::mutex> lock(msg_mutex_); if (observed_msg_queue_.empty()) { return dummy_msg_; } return *observed_msg_queue_.front(); } template <typename T> auto Blocker<T>::GetLatestObservedPtr() const -> const MessagePtr { std::lock_guard<std::mutex> lock(msg_mutex_); if (observed_msg_queue_.empty()) { return nullptr; } return observed_msg_queue_.front(); } template <typename T> auto Blocker<T>::GetOldestObservedPtr() const -> const MessagePtr { std::lock_guard<std::mutex> lock(msg_mutex_); if (observed_msg_queue_.empty()) { return nullptr; } return observed_msg_queue_.back(); } template <typename T> auto Blocker<T>::GetLatestPublishedPtr() const -> const MessagePtr { std::lock_guard<std::mutex> lock(msg_mutex_); if (published_msg_queue_.empty()) { return nullptr; } return published_msg_queue_.front(); } template <typename T> auto Blocker<T>::ObservedBegin() const -> Iterator { return observed_msg_queue_.begin(); } template <typename T> auto Blocker<T>::ObservedEnd() const -> Iterator { return observed_msg_queue_.end(); } template <typename T> size_t Blocker<T>::capacity() const { return attr_.capacity; } template <typename T> void Blocker<T>::set_capacity(size_t capacity) { std::lock_guard<std::mutex> lock(msg_mutex_); attr_.capacity = capacity; while (published_msg_queue_.size() > capacity) { published_msg_queue_.pop_back(); } } template <typename T> const std::string& Blocker<T>::channel_name() const { return attr_.channel_name; } template <typename T> void Blocker<T>::Enqueue(const MessagePtr& msg) { if (attr_.capacity == 0) { return; } std::lock_guard<std::mutex> lock(msg_mutex_); published_msg_queue_.push_front(msg); while (published_msg_queue_.size() > attr_.capacity) { published_msg_queue_.pop_back(); } } template <typename T> void Blocker<T>::Notify(const MessagePtr& msg) { std::lock_guard<std::mutex> lock(cb_mutex_); for (const auto& item : published_callbacks_) { item.second(msg); } } } // namespace blocker } // namespace cyber } // namespace apollo #endif // CYBER_BLOCKER_BLOCKER_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/blocker/blocker_manager.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef CYBER_BLOCKER_BLOCKER_MANAGER_H_ #define CYBER_BLOCKER_BLOCKER_MANAGER_H_ #include <memory> #include <mutex> #include <string> #include <unordered_map> #include "cyber/blocker/blocker.h" namespace apollo { namespace cyber { namespace blocker { class BlockerManager { public: using BlockerMap = std::unordered_map<std::string, std::shared_ptr<BlockerBase>>; virtual ~BlockerManager(); static const std::shared_ptr<BlockerManager>& Instance() { static auto instance = std::shared_ptr<BlockerManager>(new BlockerManager()); return instance; } template <typename T> bool Publish(const std::string& channel_name, const typename Blocker<T>::MessagePtr& msg); template <typename T> bool Publish(const std::string& channel_name, const typename Blocker<T>::MessageType& msg); template <typename T> bool Subscribe(const std::string& channel_name, size_t capacity, const std::string& callback_id, const typename Blocker<T>::Callback& callback); template <typename T> bool Unsubscribe(const std::string& channel_name, const std::string& callback_id); template <typename T> std::shared_ptr<Blocker<T>> GetBlocker(const std::string& channel_name); template <typename T> std::shared_ptr<Blocker<T>> GetOrCreateBlocker(const BlockerAttr& attr); void Observe(); void Reset(); private: BlockerManager(); BlockerManager(const BlockerManager&) = delete; BlockerManager& operator=(const BlockerManager&) = delete; BlockerMap blockers_; std::mutex blocker_mutex_; }; template <typename T> bool BlockerManager::Publish(const std::string& channel_name, const typename Blocker<T>::MessagePtr& msg) { auto blocker = GetOrCreateBlocker<T>(BlockerAttr(channel_name)); if (blocker == nullptr) { return false; } blocker->Publish(msg); return true; } template <typename T> bool BlockerManager::Publish(const std::string& channel_name, const typename Blocker<T>::MessageType& msg) { auto blocker = GetOrCreateBlocker<T>(BlockerAttr(channel_name)); if (blocker == nullptr) { return false; } blocker->Publish(msg); return true; } template <typename T> bool BlockerManager::Subscribe(const std::string& channel_name, size_t capacity, const std::string& callback_id, const typename Blocker<T>::Callback& callback) { auto blocker = GetOrCreateBlocker<T>(BlockerAttr(capacity, channel_name)); if (blocker == nullptr) { return false; } return blocker->Subscribe(callback_id, callback); } template <typename T> bool BlockerManager::Unsubscribe(const std::string& channel_name, const std::string& callback_id) { auto blocker = GetBlocker<T>(channel_name); if (blocker == nullptr) { return false; } return blocker->Unsubscribe(callback_id); } template <typename T> std::shared_ptr<Blocker<T>> BlockerManager::GetBlocker( const std::string& channel_name) { std::shared_ptr<Blocker<T>> blocker = nullptr; { std::lock_guard<std::mutex> lock(blocker_mutex_); auto search = blockers_.find(channel_name); if (search != blockers_.end()) { blocker = std::dynamic_pointer_cast<Blocker<T>>(search->second); } } return blocker; } template <typename T> std::shared_ptr<Blocker<T>> BlockerManager::GetOrCreateBlocker( const BlockerAttr& attr) { std::shared_ptr<Blocker<T>> blocker = nullptr; { std::lock_guard<std::mutex> lock(blocker_mutex_); auto search = blockers_.find(attr.channel_name); if (search != blockers_.end()) { blocker = std::dynamic_pointer_cast<Blocker<T>>(search->second); } else { blocker = std::make_shared<Blocker<T>>(attr); blockers_[attr.channel_name] = blocker; } } return blocker; } } // namespace blocker } // namespace cyber } // namespace apollo #endif // CYBER_BLOCKER_BLOCKER_MANAGER_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/blocker/blocker_manager_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/blocker/blocker_manager.h" #include "gtest/gtest.h" #include "cyber/proto/unit_test.pb.h" #include "cyber/blocker/intra_reader.h" #include "cyber/blocker/intra_writer.h" namespace apollo { namespace cyber { namespace blocker { using apollo::cyber::proto::UnitTest; void cb(const std::shared_ptr<UnitTest>& msg_ptr) { UNUSED(msg_ptr); } TEST(BlockerTest, blocker_manager_test) { auto block_mgr = BlockerManager::Instance(); Blocker<UnitTest>::MessageType msgtype; block_mgr->Publish<UnitTest>("ch1", msgtype); block_mgr->Subscribe<UnitTest>("ch1", 10, "cb1", cb); auto blocker = block_mgr->GetOrCreateBlocker<UnitTest>(BlockerAttr("ch1")); EXPECT_NE(blocker, nullptr); block_mgr->Unsubscribe<UnitTest>("ch1", "cb1"); block_mgr->Subscribe<UnitTest>("ch_null", 10, "cb1", cb); block_mgr->Observe(); block_mgr->Reset(); } TEST(BlockerTest, blocker_intra_writer) { proto::RoleAttributes role_attr; auto msg_ptr = std::make_shared<UnitTest>(); UnitTest msg; IntraWriter<UnitTest> writer(role_attr); EXPECT_FALSE(writer.Write(msg_ptr)); EXPECT_TRUE(writer.Init()); EXPECT_TRUE(writer.Init()); EXPECT_TRUE(writer.Write(msg_ptr)); writer.Shutdown(); writer.Shutdown(); } TEST(BlockerTest, blocker_intra_reader) { auto block_mgr = BlockerManager::Instance(); Blocker<UnitTest>::MessageType msgtype; block_mgr->Publish<UnitTest>("ch1", msgtype); proto::RoleAttributes role_attr; auto msg = std::make_shared<UnitTest>(); IntraWriter<UnitTest> writer(role_attr); writer.Init(); writer.Write(msg); IntraReader<UnitTest> reader(role_attr, cb); reader.Init(); reader.Init(); reader.SetHistoryDepth(10); EXPECT_EQ(10, reader.GetHistoryDepth()); reader.Observe(); reader.Begin(); reader.End(); EXPECT_TRUE(reader.HasReceived()); block_mgr->GetOrCreateBlocker<UnitTest>(BlockerAttr("ch1")); reader.Observe(); EXPECT_FALSE(reader.Empty()); reader.ClearData(); EXPECT_TRUE(reader.Empty()); block_mgr->Reset(); EXPECT_TRUE(reader.Empty()); EXPECT_FALSE(reader.HasReceived()); reader.GetLatestObserved(); reader.GetOldestObserved(); reader.SetHistoryDepth(10); EXPECT_EQ(reader.GetHistoryDepth(), 0); reader.ClearData(); reader.Shutdown(); } } // namespace blocker } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/blocker/blocker_manager.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/blocker/blocker_manager.h" namespace apollo { namespace cyber { namespace blocker { BlockerManager::BlockerManager() {} BlockerManager::~BlockerManager() { blockers_.clear(); } void BlockerManager::Observe() { std::lock_guard<std::mutex> lock(blocker_mutex_); for (auto& item : blockers_) { item.second->Observe(); } } void BlockerManager::Reset() { std::lock_guard<std::mutex> lock(blocker_mutex_); for (auto& item : blockers_) { item.second->Reset(); } blockers_.clear(); } } // namespace blocker } // namespace cyber } // namespace apollo
0