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/modules
apollo_public_repos/apollo/modules/monitor/monitor.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") cc_library( name = "monitor", includes = ["include"], hdrs = glob(["include/**/*.h"]), srcs = glob(["lib/**/*.so*"]), include_prefix = "modules/monitor", strip_include_prefix = "include", visibility = ["//visibility:public"], )
0
apollo_public_repos/apollo/modules
apollo_public_repos/apollo/modules/monitor/monitor.cc
/****************************************************************************** * Copyright 2017 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 "modules/monitor/monitor.h" #include "cyber/time/clock.h" #include "modules/monitor/common/monitor_manager.h" #include "modules/monitor/hardware/esdcan_monitor.h" #include "modules/monitor/hardware/gps_monitor.h" #include "modules/monitor/hardware/resource_monitor.h" #include "modules/monitor/hardware/socket_can_monitor.h" #include "modules/monitor/software/camera_monitor.h" #include "modules/monitor/software/channel_monitor.h" #include "modules/monitor/software/functional_safety_monitor.h" #include "modules/monitor/software/latency_monitor.h" #include "modules/monitor/software/localization_monitor.h" #include "modules/monitor/software/module_monitor.h" #include "modules/monitor/software/process_monitor.h" #include "modules/monitor/software/recorder_monitor.h" #include "modules/monitor/software/summary_monitor.h" DEFINE_bool(enable_functional_safety, true, "Whether to enable functional safety check."); namespace apollo { namespace monitor { bool Monitor::Init() { MonitorManager::Instance()->Init(node_); // Only the one CAN card corresponding to current mode will take effect. runners_.emplace_back(new EsdCanMonitor()); runners_.emplace_back(new SocketCanMonitor()); // To enable the GpsMonitor, you must add FLAGS_gps_component_name to the // mode's monitored_components. runners_.emplace_back(new GpsMonitor()); // To enable the LocalizationMonitor, you must add // FLAGS_localization_component_name to the mode's monitored_components. runners_.emplace_back(new LocalizationMonitor()); // To enable the CameraMonitor, you must add // FLAGS_camera_component_name to the mode's monitored_components. runners_.emplace_back(new CameraMonitor()); // Monitor if processes are running. runners_.emplace_back(new ProcessMonitor()); // Monitor if modules are running. runners_.emplace_back(new ModuleMonitor()); // Monitor message processing latencies across modules const std::shared_ptr<LatencyMonitor> latency_monitor(new LatencyMonitor()); runners_.emplace_back(latency_monitor); // Monitor if channel messages are updated in time. runners_.emplace_back(new ChannelMonitor(latency_monitor)); // Monitor if resources are sufficient. runners_.emplace_back(new ResourceMonitor()); // Monitor all changes made by each sub-monitor, and summarize to a final // overall status. runners_.emplace_back(new SummaryMonitor()); // Check functional safety according to the summary. if (FLAGS_enable_functional_safety) { runners_.emplace_back(new FunctionalSafetyMonitor()); } return true; } bool Monitor::Proc() { const double current_time = apollo::cyber::Clock::NowInSeconds(); if (!MonitorManager::Instance()->StartFrame(current_time)) { return false; } for (auto& runner : runners_) { runner->Tick(current_time); } MonitorManager::Instance()->EndFrame(); return true; } } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/hardware/esdcan_monitor.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 "modules/monitor/hardware/esdcan_monitor.h" #include <string> #if USE_ESD_CAN #include "esd_can/include/ntcan.h" #endif #include "cyber/common/file.h" #include "cyber/common/log.h" #include "modules/common/util/map_util.h" #include "modules/monitor/common/monitor_manager.h" #include "modules/monitor/software/summary_monitor.h" DEFINE_int32(esdcan_id, 0, "ESD CAN id."); DEFINE_string(esdcan_monitor_name, "EsdCanMonitor", "Name of the CAN monitor."); DEFINE_double(esdcan_monitor_interval, 3, "CAN status checking interval (s)."); DEFINE_string(esdcan_component_name, "ESD-CAN", "Name of the ESD CAN component in SystemStatus."); namespace apollo { namespace monitor { namespace { #if USE_ESD_CAN std::string StatusString(const NTCAN_RESULT ntstatus) { switch (ntstatus) { case NTCAN_SUCCESS: return "NTCAN_SUCCESS"; case NTCAN_RX_TIMEOUT: return "NTCAN_RX_TIMEOUT"; case NTCAN_TX_TIMEOUT: return "NTCAN_TX_TIMEOUT"; case NTCAN_TX_ERROR: return "NTCAN_TX_ERROR"; case NTCAN_CONTR_OFF_BUS: return "NTCAN_CONTR_OFF_BUS"; case NTCAN_CONTR_BUSY: return "NTCAN_CONTR_BUSY"; case NTCAN_CONTR_WARN: return "NTCAN_CONTR_WARN"; case NTCAN_NO_ID_ENABLED: return "NTCAN_NO_ID_ENABLED"; case NTCAN_ID_ALREADY_ENABLED: return "NTCAN_ID_ALREADY_ENABLED"; case NTCAN_ID_NOT_ENABLED: return "NTCAN_ID_NOT_ENABLED"; case NTCAN_INVALID_FIRMWARE: return "NTCAN_INVALID_FIRMWARE"; case NTCAN_MESSAGE_LOST: return "NTCAN_MESSAGE_LOST"; case NTCAN_INVALID_PARAMETER: return "NTCAN_INVALID_PARAMETER"; case NTCAN_INVALID_HANDLE: return "NTCAN_INVALID_HANDLE"; case NTCAN_NET_NOT_FOUND: return "NTCAN_NET_NOT_FOUND"; case NTCAN_INSUFFICIENT_RESOURCES: return "NTCAN_INSUFFICIENT_RESOURCES"; #ifdef NTCAN_IO_INCOMPLETE case NTCAN_IO_INCOMPLETE: return "NTCAN_IO_INCOMPLETE"; #endif #ifdef NTCAN_IO_PENDING case NTCAN_IO_PENDING: return "NTCAN_IO_PENDING"; #endif #ifdef NTCAN_INVALID_HARDWARE case NTCAN_INVALID_HARDWARE: return "NTCAN_INVALID_HARDWARE"; #endif #ifdef NTCAN_PENDING_WRITE case NTCAN_PENDING_WRITE: return "NTCAN_PENDING_WRITE"; #endif #ifdef NTCAN_PENDING_READ case NTCAN_PENDING_READ: return "NTCAN_PENDING_READ"; #endif #ifdef NTCAN_INVALID_DRIVER case NTCAN_INVALID_DRIVER: return "NTCAN_INVALID_DRIVER"; #endif #ifdef NTCAN_OPERATION_ABORTED case NTCAN_OPERATION_ABORTED: return "NTCAN_OPERATION_ABORTED"; #endif #ifdef NTCAN_WRONG_DEVICE_STATE case NTCAN_WRONG_DEVICE_STATE: return "NTCAN_WRONG_DEVICE_STATE"; #endif #ifdef NTCAN_HANDLE_FORCED_CLOSE case NTCAN_HANDLE_FORCED_CLOSE: return "NTCAN_HANDLE_FORCED_CLOSE"; #endif #ifdef NTCAN_NOT_IMPLEMENTED case NTCAN_NOT_IMPLEMENTED: return "NTCAN_NOT_IMPLEMENTED"; #endif #ifdef NTCAN_NOT_SUPPORTED case NTCAN_NOT_SUPPORTED: return "NTCAN_NOT_SUPPORTED"; #endif #ifdef NTCAN_SOCK_CONN_TIMEOUT case NTCAN_SOCK_CONN_TIMEOUT: return "NTCAN_SOCK_CONN_TIMEOUT"; #endif #ifdef NTCAN_SOCK_CMD_TIMEOUT case NTCAN_SOCK_CMD_TIMEOUT: return "NTCAN_SOCK_CMD_TIMEOUT"; #endif #ifdef NTCAN_SOCK_HOST_NOT_FOUND case NTCAN_SOCK_HOST_NOT_FOUND: return "NTCAN_SOCK_HOST_NOT_FOUND"; #endif #ifdef NTCAN_CONTR_ERR_PASSIVE case NTCAN_CONTR_ERR_PASSIVE: return "NTCAN_CONTR_ERR_PASSIVE"; #endif #ifdef NTCAN_ERROR_NO_BAUDRATE case NTCAN_ERROR_NO_BAUDRATE: return "NTCAN_ERROR_NO_BAUDRATE"; #endif #ifdef NTCAN_ERROR_LOM case NTCAN_ERROR_LOM: return "NTCAN_ERROR_LOM"; #endif default: break; } return "NTCAN_UNKNOWN"; } NTCAN_RESULT EsdCanTest(const int can_id, NTCAN_HANDLE* handle) { NTCAN_RESULT ret = canOpen(can_id, 0, 1, 1, 0, 0, handle); if (ret == NTCAN_SUCCESS) { AINFO << "Successfully opened ESD-CAN device " << can_id; } else { AERROR << "Failed to open ESD-CAN device " << can_id << ", error: " << ret << " (" << StatusString(ret) << ")"; return ret; } CAN_IF_STATUS if_status; ret = canStatus(*handle, &if_status); if (ret != NTCAN_SUCCESS) { AERROR << "Cannot get status of ESD-CAN, ret=" << ret << " (" << StatusString(ret) << ")"; return ret; } NTCAN_BUS_STATISTIC stats; ret = canIoctl(*handle, NTCAN_IOCTL_GET_BUS_STATISTIC, &stats); if (ret != NTCAN_SUCCESS) { AERROR << "NTCAN_IOCTL_GET_BUS_STATISTIC failed for device with error: " << ret << " (" << StatusString(ret) << ")"; return ret; } NTCAN_CTRL_STATE ctrl_state; ret = canIoctl(*handle, NTCAN_IOCTL_GET_CTRL_STATUS, &ctrl_state); if (ret != NTCAN_SUCCESS) { AERROR << "NTCAN_IOCTL_GET_CTRL_STATUS failed for device with error: " << ret << " (" << StatusString(ret) << ")"; return ret; } NTCAN_BITRATE bitrate; ret = canIoctl(*handle, NTCAN_IOCTL_GET_BITRATE_DETAILS, &bitrate); if (ret != NTCAN_SUCCESS) { AERROR << "NTCAN_IOCTL_GET_BITRATE_ for device with error: " << ret << " (" << StatusString(ret) << ")"; return ret; } return ret; } void EsdCanTest(const int can_id, ComponentStatus* status) { NTCAN_HANDLE handle; const NTCAN_RESULT ret = EsdCanTest(can_id, &handle); canClose(handle); SummaryMonitor::EscalateStatus( ret == NTCAN_SUCCESS ? ComponentStatus::OK : ComponentStatus::ERROR, StatusString(ret), status); } #else // USE_ESD_CAN is not set, do dummy check. void EsdCanTest(const int can_id, ComponentStatus* status) { SummaryMonitor::EscalateStatus(ComponentStatus::ERROR, "USE_ESD_CAN is not defined during compiling", status); } #endif } // namespace EsdCanMonitor::EsdCanMonitor() : RecurrentRunner(FLAGS_esdcan_monitor_name, FLAGS_esdcan_monitor_interval) {} void EsdCanMonitor::RunOnce(const double current_time) { Component* component = apollo::common::util::FindOrNull( *MonitorManager::Instance()->GetStatus()->mutable_components(), FLAGS_esdcan_component_name); if (component == nullptr) { // Canbus is not monitored in current mode, skip. return; } auto* status = component->mutable_other_status(); status->clear_status(); EsdCanTest(FLAGS_esdcan_id, status); } } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/hardware/gps_monitor.cc
/****************************************************************************** * Copyright 2017 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 "modules/monitor/hardware/gps_monitor.h" #include "cyber/common/log.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/util/map_util.h" #include "modules/common_msgs/sensor_msgs/gnss_best_pose.pb.h" #include "modules/monitor/common/monitor_manager.h" #include "modules/monitor/software/summary_monitor.h" DEFINE_string(gps_monitor_name, "GpsMonitor", "Name of the GPS monitor."); DEFINE_double(gps_monitor_interval, 3, "GPS status checking interval (s)."); DEFINE_string(gps_component_name, "GPS", "GPS component name."); namespace apollo { namespace monitor { using apollo::drivers::gnss::GnssBestPose; using apollo::drivers::gnss::SolutionType; GpsMonitor::GpsMonitor() : RecurrentRunner(FLAGS_gps_monitor_name, FLAGS_gps_monitor_interval) {} void GpsMonitor::RunOnce(const double current_time) { auto manager = MonitorManager::Instance(); Component* component = apollo::common::util::FindOrNull( *manager->GetStatus()->mutable_components(), FLAGS_gps_component_name); if (component == nullptr) { // GPS is not monitored in current mode, skip. return; } ComponentStatus* component_status = component->mutable_other_status(); component_status->clear_status(); static auto gnss_best_pose_reader = manager->CreateReader<GnssBestPose>(FLAGS_gnss_best_pose_topic); gnss_best_pose_reader->Observe(); const auto gnss_best_pose_status = gnss_best_pose_reader->GetLatestObserved(); if (gnss_best_pose_status == nullptr) { SummaryMonitor::EscalateStatus(ComponentStatus::ERROR, "No GnssBestPose message", component_status); return; } switch (gnss_best_pose_status->sol_type()) { case SolutionType::NARROW_INT: SummaryMonitor::EscalateStatus(ComponentStatus::OK, "", component_status); break; case SolutionType::SINGLE: SummaryMonitor::EscalateStatus( ComponentStatus::WARN, "SolutionType is SINGLE", component_status); break; default: SummaryMonitor::EscalateStatus(ComponentStatus::ERROR, "SolutionType is wrong", component_status); break; } } } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/hardware/socket_can_monitor.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 "modules/monitor/hardware/socket_can_monitor.h" #include <linux/can.h> #include <linux/can/raw.h> #include <net/if.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #include <string> #include "cyber/common/file.h" #include "cyber/common/log.h" #include "modules/common/util/map_util.h" #include "modules/monitor/common/monitor_manager.h" #include "modules/monitor/software/summary_monitor.h" DEFINE_string(socket_can_monitor_name, "SocketCanMonitor", "Name of the CAN monitor."); DEFINE_double(socket_can_monitor_interval, 3, "Socket CAN status checking interval seconds."); DEFINE_string(socket_can_component_name, "SocketCAN", "Name of the Socket CAN component in SystemStatus."); namespace apollo { namespace monitor { namespace { // Test Socket CAN on an open handler. bool SocketCanHandlerTest(const int dev_handler, std::string* message) { // init config and state // 1. set receive message_id filter, ie white list struct can_filter filter[1]; filter[0].can_id = 0x000; filter[0].can_mask = CAN_SFF_MASK; int ret = setsockopt(dev_handler, SOL_CAN_RAW, CAN_RAW_FILTER, &filter, sizeof(filter)); if (ret < 0) { *message = "set message filter failed"; return false; } // 2. enable reception of can frames. const int enable = 1; ret = setsockopt(dev_handler, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &enable, sizeof(enable)); if (ret < 0) { *message = "Enable reception of can frames failed"; return false; } struct ifreq ifr; std::strncpy(ifr.ifr_name, "can0", IFNAMSIZ); if (ioctl(dev_handler, SIOCGIFINDEX, &ifr) < 0) { *message = "ioctl failed"; return false; } // bind socket to network interface struct sockaddr_can addr; addr.can_family = AF_CAN; addr.can_ifindex = ifr.ifr_ifindex; ret = bind(dev_handler, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)); if (ret < 0) { *message = "bind socket can failed"; return false; } return true; } // Open a Socket CAN handler and test. bool SocketCanTest(std::string* message) { const int dev_handler = socket(PF_CAN, SOCK_RAW, CAN_RAW); if (dev_handler < 0) { *message = "Open can device failed"; return false; } const bool ret = SocketCanHandlerTest(dev_handler, message); close(dev_handler); return ret; } } // namespace SocketCanMonitor::SocketCanMonitor() : RecurrentRunner(FLAGS_socket_can_monitor_name, FLAGS_socket_can_monitor_interval) {} void SocketCanMonitor::RunOnce(const double current_time) { auto manager = MonitorManager::Instance(); Component* component = apollo::common::util::FindOrNull( *manager->GetStatus()->mutable_components(), FLAGS_socket_can_component_name); if (component == nullptr) { // Canbus is not monitored in current mode, skip. return; } auto* status = component->mutable_other_status(); status->clear_status(); std::string message; const bool ret = SocketCanTest(&message); SummaryMonitor::EscalateStatus( ret ? ComponentStatus::OK : ComponentStatus::ERROR, message, status); } } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/hardware/socket_can_monitor.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. *****************************************************************************/ #pragma once #include "modules/monitor/common/recurrent_runner.h" namespace apollo { namespace monitor { class SocketCanMonitor : public RecurrentRunner { public: SocketCanMonitor(); void RunOnce(const double current_time) override; }; } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/hardware/resource_monitor.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 "modules/monitor/hardware/resource_monitor.h" #include <algorithm> #include <string> #include <unordered_map> #include <vector> #include <boost/filesystem.hpp> #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" #include "cyber/common/file.h" #include "cyber/common/log.h" #include "gflags/gflags.h" #include "modules/common/util/map_util.h" #include "modules/monitor/common/monitor_manager.h" #include "modules/monitor/software/summary_monitor.h" DEFINE_string(resource_monitor_name, "ResourceMonitor", "Name of the resource monitor."); DEFINE_double(resource_monitor_interval, 5, "Topic status checking interval (s)."); namespace apollo { namespace monitor { namespace { bool GetPIDByCmdLine(const std::string& process_dag_path, int* pid) { const std::string system_proc_path = "/proc"; const std::string proc_cmdline_path = "/cmdline"; const auto dirs = cyber::common::ListSubPaths(system_proc_path); std::string cmd_line; for (const auto& dir_name : dirs) { if (!std::all_of(dir_name.begin(), dir_name.end(), isdigit)) { continue; } *pid = std::stoi(dir_name); std::ifstream cmdline_file( absl::StrCat(system_proc_path, "/", dir_name, proc_cmdline_path)); std::getline(cmdline_file, cmd_line); if (absl::StrContains(cmd_line, process_dag_path)) { return true; } } return false; } std::vector<std::string> GetStatsLines(const std::string& stat_file, const int line_count) { std::vector<std::string> stats_lines; std::ifstream buffer(stat_file); for (int line_num = 0; line_num < line_count; ++line_num) { std::string line; std::getline(buffer, line); if (line.empty()) { break; } stats_lines.push_back(line); } return stats_lines; } float GetMemoryUsage(const int pid, const std::string& process_name) { const std::string memory_stat_file = absl::StrCat("/proc/", pid, "/statm"); const uint32_t page_size_kb = (sysconf(_SC_PAGE_SIZE) >> 10); const int resident_idx = 1, gb_2_kb = (1 << 20); constexpr static int kMemoryInfo = 0; const auto stat_lines = GetStatsLines(memory_stat_file, kMemoryInfo + 1); if (stat_lines.size() <= kMemoryInfo) { AERROR << "failed to load contents from " << memory_stat_file; return 0.f; } const std::vector<std::string> stats = absl::StrSplit(stat_lines[kMemoryInfo], ' ', absl::SkipWhitespace()); if (stats.size() <= resident_idx) { AERROR << "failed to get memory info for process " << process_name; return 0.f; } return static_cast<float>(std::stoll(stats[resident_idx]) * page_size_kb) / gb_2_kb; } float GetCPUUsage(const int pid, const std::string& process_name, std::unordered_map<std::string, uint64_t>* prev_jiffies_map) { const std::string cpu_stat_file = absl::StrCat("/proc/", pid, "/stat"); const int hertz = sysconf(_SC_CLK_TCK); const int utime = 13, stime = 14, cutime = 15, cstime = 16; constexpr static int kCpuInfo = 0; const auto stat_lines = GetStatsLines(cpu_stat_file, kCpuInfo + 1); if (stat_lines.size() <= kCpuInfo) { AERROR << "failed to load contents from " << cpu_stat_file; return 0.f; } const std::vector<std::string> stats = absl::StrSplit(stat_lines[kCpuInfo], ' ', absl::SkipWhitespace()); if (stats.size() <= cstime) { AERROR << "failed to get CPU info for process " << process_name; return 0.f; } const uint64_t jiffies = std::stoll(stats[utime]) + std::stoll(stats[stime]) + std::stoll(stats[cutime]) + std::stoll(stats[cstime]); const uint64_t prev_jiffies = (*prev_jiffies_map)[process_name]; (*prev_jiffies_map)[process_name] = jiffies; if (prev_jiffies == 0) { return 0.f; } return 100.f * (static_cast<float>(jiffies - prev_jiffies) / hertz / static_cast<float>(FLAGS_resource_monitor_interval)); } uint64_t GetSystemMemoryValueFromLine(std::string stat_line) { constexpr static int kMemoryValueIdx = 1; const std::vector<std::string> stats = absl::StrSplit(stat_line, ' ', absl::SkipWhitespace()); if (stats.size() <= kMemoryValueIdx) { AERROR << "failed to parse memory from line " << stat_line; return 0; } return std::stoll(stats[kMemoryValueIdx]); } float GetSystemMemoryUsage() { const std::string system_mem_stat_file = "/proc/meminfo"; const int mem_total = 0, mem_free = 1, buffers = 3, cached = 4, swap_total = 14, swap_free = 15, slab = 21; const auto stat_lines = GetStatsLines(system_mem_stat_file, slab + 1); if (stat_lines.size() <= slab) { AERROR << "failed to load contents from " << system_mem_stat_file; return 0.f; } const auto total_memory = GetSystemMemoryValueFromLine(stat_lines[mem_total]) + GetSystemMemoryValueFromLine(stat_lines[swap_total]); int64_t used_memory = total_memory; for (int cur_line = mem_free; cur_line <= slab; ++cur_line) { if (cur_line == mem_free || cur_line == buffers || cur_line == cached || cur_line == swap_free || cur_line == slab) { used_memory -= GetSystemMemoryValueFromLine(stat_lines[cur_line]); } } return 100.f * (static_cast<float>(used_memory) / total_memory); } float GetSystemCPUUsage() { const std::string system_cpu_stat_file = "/proc/stat"; const int users = 1, system = 3, total = 7; constexpr static int kSystemCpuInfo = 0; static uint64_t prev_jiffies = 0, prev_work_jiffies = 0; const auto stat_lines = GetStatsLines(system_cpu_stat_file, kSystemCpuInfo + 1); if (stat_lines.size() <= kSystemCpuInfo) { AERROR << "failed to load contents from " << system_cpu_stat_file; return 0.f; } const std::vector<std::string> jiffies_stats = absl::StrSplit(stat_lines[kSystemCpuInfo], ' ', absl::SkipWhitespace()); if (jiffies_stats.size() <= total) { AERROR << "failed to get system CPU info from " << system_cpu_stat_file; return 0.f; } uint64_t jiffies = 0, work_jiffies = 0; for (int cur_stat = users; cur_stat <= total; ++cur_stat) { const auto cur_stat_value = std::stoll(jiffies_stats[cur_stat]); jiffies += cur_stat_value; if (cur_stat <= system) { work_jiffies += cur_stat_value; } } const uint64_t tmp_prev_jiffies = prev_jiffies; const uint64_t tmp_prev_work_jiffies = prev_work_jiffies; prev_jiffies = jiffies; prev_work_jiffies = work_jiffies; if (tmp_prev_jiffies == 0) { return 0.f; } return 100.f * (static_cast<float>(work_jiffies - tmp_prev_work_jiffies) / (jiffies - tmp_prev_jiffies)); } float GetSystemDiskload(const std::string& device_name) { const std::string disks_stat_file = "/proc/diskstats"; const int device = 2, in_out_ms = 12; const int seconds_to_ms = 1000; constexpr static int kDiskInfo = 128; static uint64_t prev_disk_stats = 0; const auto stat_lines = GetStatsLines(disks_stat_file, kDiskInfo); uint64_t disk_stats = 0; for (const auto& line : stat_lines) { const std::vector<std::string> stats = absl::StrSplit(line, ' ', absl::SkipWhitespace()); if (stats[device] == device_name) { disk_stats = std::stoll(stats[in_out_ms]); break; } } const uint64_t tmp_prev_disk_stats = prev_disk_stats; prev_disk_stats = disk_stats; if (tmp_prev_disk_stats == 0) { return 0.f; } return 100.f * (static_cast<float>(disk_stats - tmp_prev_disk_stats) / static_cast<float>(FLAGS_resource_monitor_interval * seconds_to_ms)); } } // namespace ResourceMonitor::ResourceMonitor() : RecurrentRunner(FLAGS_resource_monitor_name, FLAGS_resource_monitor_interval) {} void ResourceMonitor::RunOnce(const double current_time) { auto manager = MonitorManager::Instance(); const auto& mode = manager->GetHMIMode(); auto* components = manager->GetStatus()->mutable_components(); for (const auto& iter : mode.monitored_components()) { const std::string& name = iter.first; const auto& config = iter.second; if (config.has_resource()) { UpdateStatus(config.resource(), components->at(name).mutable_resource_status()); } } } void ResourceMonitor::UpdateStatus( const apollo::dreamview::ResourceMonitorConfig& config, ComponentStatus* status) { status->clear_status(); CheckDiskSpace(config, status); CheckCPUUsage(config, status); CheckMemoryUsage(config, status); CheckDiskLoads(config, status); SummaryMonitor::EscalateStatus(ComponentStatus::OK, "", status); } void ResourceMonitor::CheckDiskSpace( const apollo::dreamview::ResourceMonitorConfig& config, ComponentStatus* status) { // Monitor available disk space. for (const auto& disk_space : config.disk_spaces()) { for (const auto& path : cyber::common::Glob(disk_space.path())) { const auto space = boost::filesystem::space(path); const int available_gb = static_cast<int>(space.available >> 30); if (available_gb < disk_space.insufficient_space_error()) { const std::string err = absl::StrCat(path, " has insufficient space: ", available_gb, "GB < ", disk_space.insufficient_space_error()); SummaryMonitor::EscalateStatus(ComponentStatus::ERROR, err, status); } else if (available_gb < disk_space.insufficient_space_warning()) { const std::string err = absl::StrCat(path, " has insufficient space: ", available_gb, "GB < ", disk_space.insufficient_space_warning()); SummaryMonitor::EscalateStatus(ComponentStatus::WARN, err, status); } } } } void ResourceMonitor::CheckCPUUsage( const apollo::dreamview::ResourceMonitorConfig& config, ComponentStatus* status) { for (const auto& cpu_usage : config.cpu_usages()) { const auto process_dag_path = cpu_usage.process_dag_path(); float cpu_usage_value = 0.f; if (process_dag_path.empty()) { cpu_usage_value = GetSystemCPUUsage(); } else { int pid = 0; if (GetPIDByCmdLine(process_dag_path, &pid)) { static std::unordered_map<std::string, uint64_t> prev_jiffies_map; if (prev_jiffies_map.find(process_dag_path) == prev_jiffies_map.end()) { prev_jiffies_map[process_dag_path] = 0; } cpu_usage_value = GetCPUUsage(pid, process_dag_path, &prev_jiffies_map); } } const auto high_cpu_warning = cpu_usage.high_cpu_usage_warning(); const auto high_cpu_error = cpu_usage.high_cpu_usage_error(); if (cpu_usage_value > high_cpu_error) { const std::string err = absl::StrCat( process_dag_path, " has high cpu usage: ", cpu_usage_value, "% > ", high_cpu_error, "%"); SummaryMonitor::EscalateStatus(ComponentStatus::ERROR, err, status); } else if (cpu_usage_value > high_cpu_warning) { const std::string warn = absl::StrCat( process_dag_path, " has high cpu usage: ", cpu_usage_value, "% > ", high_cpu_warning, "%"); SummaryMonitor::EscalateStatus(ComponentStatus::WARN, warn, status); } } } void ResourceMonitor::CheckMemoryUsage( const apollo::dreamview::ResourceMonitorConfig& config, ComponentStatus* status) { for (const auto& memory_usage : config.memory_usages()) { const auto process_dag_path = memory_usage.process_dag_path(); float memory_usage_value = 0.f; if (process_dag_path.empty()) { memory_usage_value = GetSystemMemoryUsage(); } else { int pid = 0; if (GetPIDByCmdLine(process_dag_path, &pid)) { memory_usage_value = GetMemoryUsage(pid, process_dag_path); } } const auto high_memory_warning = memory_usage.high_memory_usage_warning(); const auto high_memory_error = memory_usage.high_memory_usage_error(); if (memory_usage_value > static_cast<float>(high_memory_error)) { const std::string err = absl::StrCat( process_dag_path, " has high memory usage: ", memory_usage_value, " > ", high_memory_error); SummaryMonitor::EscalateStatus(ComponentStatus::ERROR, err, status); } else if (memory_usage_value > static_cast<float>(high_memory_warning)) { const std::string warn = absl::StrCat( process_dag_path, " has high memory usage: ", memory_usage_value, " > ", high_memory_warning); SummaryMonitor::EscalateStatus(ComponentStatus::WARN, warn, status); } } } void ResourceMonitor::CheckDiskLoads( const apollo::dreamview::ResourceMonitorConfig& config, ComponentStatus* status) { for (const auto& disk_load : config.disk_load_usages()) { const auto disk_load_value = GetSystemDiskload(disk_load.device_name()); const auto high_disk_load_warning = disk_load.high_disk_load_warning(); const auto high_disk_load_error = disk_load.high_disk_load_error(); if (disk_load_value > static_cast<float>(high_disk_load_error)) { const std::string err = absl::StrCat( disk_load.device_name(), " has high disk load: ", disk_load_value, " > ", high_disk_load_error); SummaryMonitor::EscalateStatus(ComponentStatus::ERROR, err, status); } else if (disk_load_value > static_cast<float>(high_disk_load_warning)) { const std::string warn = absl::StrCat( disk_load.device_name(), " has high disk load: ", disk_load_value, " > ", high_disk_load_warning); SummaryMonitor::EscalateStatus(ComponentStatus::WARN, warn, status); } } } } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/hardware/esdcan_monitor.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. *****************************************************************************/ #pragma once #include "modules/monitor/common/recurrent_runner.h" namespace apollo { namespace monitor { class EsdCanMonitor : public RecurrentRunner { public: EsdCanMonitor(); void RunOnce(const double current_time) override; }; } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/hardware/resource_monitor.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. *****************************************************************************/ #pragma once #include "modules/dreamview/proto/hmi_mode.pb.h" #include "modules/monitor/common/recurrent_runner.h" #include "modules/common_msgs/monitor_msgs/system_status.pb.h" namespace apollo { namespace monitor { class ResourceMonitor : public RecurrentRunner { public: ResourceMonitor(); void RunOnce(const double current_time) override; private: static void UpdateStatus( const apollo::dreamview::ResourceMonitorConfig& config, ComponentStatus* status); static void CheckDiskSpace( const apollo::dreamview::ResourceMonitorConfig& config, ComponentStatus* status); static void CheckCPUUsage( const apollo::dreamview::ResourceMonitorConfig& config, ComponentStatus* status); static void CheckMemoryUsage( const apollo::dreamview::ResourceMonitorConfig& config, ComponentStatus* status); static void CheckDiskLoads( const apollo::dreamview::ResourceMonitorConfig& config, ComponentStatus* status); }; } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/hardware/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") load("//tools/platform:build_defs.bzl", "copts_if_esd_can", "if_esd_can") package(default_visibility = ["//visibility:public"]) MONITOR_COPTS = ['-DMODULE_NAME=\\"monitor\\"'] cc_library( name = "gps_monitor", srcs = ["gps_monitor.cc"], hdrs = ["gps_monitor.h"], copts = MONITOR_COPTS, deps = [ "//cyber", "//modules/common_msgs/sensor_msgs:gnss_best_pose_cc_proto", "//modules/monitor/common:monitor_manager", "//modules/monitor/common:recurrent_runner", "//modules/monitor/software:summary_monitor", ], ) cc_library( name = "resource_monitor", srcs = ["resource_monitor.cc"], hdrs = ["resource_monitor.h"], copts = MONITOR_COPTS, deps = [ "//modules/common/util", "//modules/dreamview/proto:hmi_mode_cc_proto", "//modules/monitor/common:monitor_manager", "//modules/monitor/common:recurrent_runner", "//modules/monitor/software:summary_monitor", "@boost", ], ) cc_library( name = "esdcan_monitor", srcs = ["esdcan_monitor.cc"], hdrs = ["esdcan_monitor.h"], copts = MONITOR_COPTS + copts_if_esd_can(), deps = [ "//modules/common/util", "//modules/monitor/common:monitor_manager", "//modules/monitor/common:recurrent_runner", "//modules/monitor/software:summary_monitor", ] + if_esd_can([ "//modules/drivers/canbus/can_client/esd:esd_can_client", ]), ) cc_library( name = "socket_can_monitor", srcs = ["socket_can_monitor.cc"], hdrs = ["socket_can_monitor.h"], copts = MONITOR_COPTS, deps = [ "//modules/common/util", "//modules/monitor/common:monitor_manager", "//modules/monitor/common:recurrent_runner", "//modules/monitor/software:summary_monitor", ], ) cpplint()
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/hardware/gps_monitor.h
/****************************************************************************** * Copyright 2017 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. *****************************************************************************/ #pragma once #include "modules/monitor/common/recurrent_runner.h" namespace apollo { namespace monitor { class GpsMonitor : public RecurrentRunner { public: GpsMonitor(); void RunOnce(const double current_time) override; }; } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/launch/monitor.launch
<cyber> <module> <name>monitor</name> <dag_conf>/apollo/modules/monitor/dag/monitor.dag</dag_conf> <process_name>monitor</process_name> </module> </cyber>
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/dag/monitor.dag
module_config { module_library : "/apollo/bazel-bin/modules/monitor/libmonitor.so" timer_components { class_name : "Monitor" config { name: "monitor" interval: 500 } } }
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/software/functional_safety_monitor.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 "modules/monitor/software/functional_safety_monitor.h" #include <string> #include "absl/strings/str_cat.h" #include "modules/monitor/common/monitor_manager.h" DEFINE_string(functional_safety_monitor_name, "FunctionalSafetyMonitor", "Name of the functional safety monitor."); DEFINE_double(safety_mode_seconds_before_estop, 10.0, "Interval before sending estop after we found critical errors."); namespace apollo { namespace monitor { namespace { bool IsSafe(const std::string& name, const ComponentStatus& status) { if (status.status() == ComponentStatus::ERROR || status.status() == ComponentStatus::FATAL) { MonitorManager::Instance()->LogBuffer().ERROR( absl::StrCat(name, " triggers safe mode: ", status.message())); return false; } return true; } } // namespace FunctionalSafetyMonitor::FunctionalSafetyMonitor() : RecurrentRunner(FLAGS_functional_safety_monitor_name, 0) {} void FunctionalSafetyMonitor::RunOnce(const double current_time) { auto* system_status = MonitorManager::Instance()->GetStatus(); // Everything looks good or has been handled properly. if (CheckSafety()) { system_status->clear_passenger_msg(); system_status->clear_safety_mode_trigger_time(); system_status->clear_require_emergency_stop(); return; } if (system_status->require_emergency_stop()) { // EStop has already been triggered. return; } // Newly entered safety mode. system_status->set_passenger_msg("Error! Please disengage."); if (!system_status->has_safety_mode_trigger_time()) { system_status->set_safety_mode_trigger_time(current_time); return; } // Trigger EStop if no action was taken in time. if (system_status->safety_mode_trigger_time() + FLAGS_safety_mode_seconds_before_estop < current_time) { system_status->set_require_emergency_stop(true); } } bool FunctionalSafetyMonitor::CheckSafety() { // We only check safety in self driving mode. auto manager = MonitorManager::Instance(); if (!manager->IsInAutonomousMode()) { return true; } // Check HMI modules status. const auto& mode = manager->GetHMIMode(); const auto& hmi_modules = manager->GetStatus()->hmi_modules(); for (const auto& iter : mode.modules()) { const std::string& module_name = iter.first; const auto& module = iter.second; if (module.required_for_safety() && !IsSafe(module_name, hmi_modules.at(module_name))) { return false; } } // Check monitored components status. const auto& components = manager->GetStatus()->components(); for (const auto& iter : mode.monitored_components()) { const std::string& component_name = iter.first; const auto& component = iter.second; if (component.required_for_safety() && !IsSafe(component_name, components.at(component_name).summary())) { return false; } } // Everything looks good. return true; } } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/software/module_monitor.cc
/****************************************************************************** * Copyright 2020 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 "modules/monitor/software/module_monitor.h" #include "absl/flags/flag.h" #include "cyber/common/file.h" #include "cyber/common/log.h" #include "modules/common/util/map_util.h" #include "modules/monitor/common/monitor_manager.h" #include "modules/monitor/software/summary_monitor.h" ABSL_FLAG(std::string, module_monitor_name, "ModuleMonitor", "Name of the modules monitor."); ABSL_FLAG(double, module_monitor_interval, 1.5, "Process status checking interval in seconds."); namespace apollo { namespace monitor { ModuleMonitor::ModuleMonitor() : RecurrentRunner(absl::GetFlag(FLAGS_module_monitor_name), absl::GetFlag(FLAGS_module_monitor_interval)) { node_manager_ = cyber::service_discovery::TopologyManager::Instance()->node_manager(); } void ModuleMonitor::RunOnce(const double current_time) { auto manager = MonitorManager::Instance(); const auto& mode = manager->GetHMIMode(); // Check monitored components. auto* components = manager->GetStatus()->mutable_components(); for (const auto& iter : mode.monitored_components()) { const std::string& name = iter.first; const auto& monitored_component = iter.second; if (monitored_component.has_module() && apollo::common::util::ContainsKey(*components, name)) { const auto& config = monitored_component.module(); auto* status = components->at(name).mutable_module_status(); UpdateStatus(config, name, status); } } } void ModuleMonitor::UpdateStatus( const apollo::dreamview::ModuleMonitorConfig& config, const std::string& module_name, ComponentStatus* status) { status->clear_status(); bool all_nodes_matched = true; for (const std::string& name : config.node_name()) { if (!node_manager_->HasNode(name)) { all_nodes_matched = false; break; } } if (all_nodes_matched) { // Working nodes are all matched. The module is running. SummaryMonitor::EscalateStatus(ComponentStatus::OK, module_name, status); return; } SummaryMonitor::EscalateStatus(ComponentStatus::FATAL, "", status); } } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/software/recorder_monitor.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. *****************************************************************************/ #pragma once #include "modules/monitor/common/recurrent_runner.h" namespace apollo { namespace monitor { class RecorderMonitor : public RecurrentRunner { public: RecorderMonitor(); void RunOnce(const double current_time) override; }; } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/software/summary_monitor.cc
/****************************************************************************** * Copyright 2017 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 "modules/monitor/software/summary_monitor.h" #include "cyber/common/log.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/util/string_util.h" #include "modules/monitor/common/monitor_manager.h" DEFINE_string(summary_monitor_name, "SummaryMonitor", "Name of the summary monitor."); DEFINE_double(system_status_publish_interval, 1, "SystemStatus publish interval."); namespace apollo { namespace monitor { void SummaryMonitor::EscalateStatus(const ComponentStatus::Status new_status, const std::string& message, ComponentStatus* current_status) { // Overwrite priority: FATAL > ERROR > WARN > OK > UNKNOWN. if (new_status > current_status->status()) { current_status->set_status(new_status); if (!message.empty()) { current_status->set_message(message); } else { current_status->clear_message(); } } } // Set interval to 0, so it runs every time when ticking. SummaryMonitor::SummaryMonitor() : RecurrentRunner(FLAGS_summary_monitor_name, 0) {} void SummaryMonitor::RunOnce(const double current_time) { auto manager = MonitorManager::Instance(); auto* status = manager->GetStatus(); // Escalate the summary status to the most severe one. for (auto& component : *status->mutable_components()) { auto* summary = component.second.mutable_summary(); const auto& process_status = component.second.process_status(); EscalateStatus(process_status.status(), process_status.message(), summary); const auto& module_status = component.second.module_status(); EscalateStatus(module_status.status(), module_status.message(), summary); const auto& channel_status = component.second.channel_status(); EscalateStatus(channel_status.status(), channel_status.message(), summary); const auto& resource_status = component.second.resource_status(); EscalateStatus(resource_status.status(), resource_status.message(), summary); const auto& other_status = component.second.other_status(); EscalateStatus(other_status.status(), other_status.message(), summary); } // Get fingerprint of current status. // Don't use DebugString() which has known bug on Map field. The string // doesn't change though the value has changed. static std::hash<std::string> hash_fn; std::string proto_bytes; status->SerializeToString(&proto_bytes); const size_t new_fp = hash_fn(proto_bytes); if (system_status_fp_ != new_fp || current_time - last_broadcast_ > FLAGS_system_status_publish_interval) { static auto writer = manager->CreateWriter<SystemStatus>(FLAGS_system_status_topic); apollo::common::util::FillHeader("SystemMonitor", status); writer->Write(*status); status->clear_header(); system_status_fp_ = new_fp; last_broadcast_ = current_time; } } } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/software/latency_monitor.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. *****************************************************************************/ #pragma once #include <memory> #include <set> #include <string> #include <tuple> #include <unordered_map> #include "modules/common/latency_recorder/proto/latency_record.pb.h" #include "modules/monitor/common/recurrent_runner.h" namespace apollo { namespace monitor { class LatencyMonitor : public RecurrentRunner { public: LatencyMonitor(); void RunOnce(const double current_time) override; bool GetFrequency(const std::string& channel_name, double* freq); private: void UpdateStat( const std::shared_ptr<apollo::common::LatencyRecordMap>& records); void PublishLatencyReport(); void AggregateLatency(); apollo::common::LatencyReport latency_report_; std::unordered_map<uint64_t, std::set<std::tuple<uint64_t, uint64_t, std::string>>> track_map_; std::unordered_map<std::string, double> freq_map_; double flush_time_ = 0.0; }; } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/software/latency_monitor.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 "modules/monitor/software/latency_monitor.h" #include <algorithm> #include <memory> #include <unordered_set> #include <utility> #include <vector> #include "absl/strings/str_cat.h" #include "cyber/common/log.h" #include "cyber/time/time.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/util/string_util.h" #include "modules/monitor/common/monitor_manager.h" #include "modules/monitor/software/summary_monitor.h" DEFINE_string(latency_monitor_name, "LatencyMonitor", "Name of the latency monitor."); DEFINE_double(latency_monitor_interval, 1.5, "Latency report interval in seconds."); DEFINE_double(latency_report_interval, 15.0, "Latency report interval in seconds."); DEFINE_int32(latency_reader_capacity, 30, "The max message numbers in latency reader queue."); namespace apollo { namespace monitor { namespace { using apollo::common::LatencyRecordMap; using apollo::common::LatencyReport; using apollo::common::LatencyStat; using apollo::common::LatencyTrack; LatencyStat GenerateStat(const std::vector<uint64_t>& numbers) { LatencyStat stat; uint64_t min_number = (1UL << 63), max_number = 0, sum = 0; for (const auto number : numbers) { min_number = std::min(min_number, number); max_number = std::max(max_number, number); sum += number; } const uint32_t sample_size = static_cast<uint32_t>(numbers.size()); stat.set_min_duration(min_number); stat.set_max_duration(max_number); stat.set_aver_duration( sample_size == 0 ? 0 : static_cast<uint64_t>(sum / sample_size)); stat.set_sample_size(sample_size); return stat; } void SetStat(const LatencyStat& src, LatencyStat* dst) { dst->set_min_duration(src.min_duration()); dst->set_max_duration(src.max_duration()); dst->set_aver_duration(src.aver_duration()); dst->set_sample_size(src.sample_size()); } void SetLatency(const std::string& latency_name, const std::vector<uint64_t>& latency_values, LatencyTrack* track) { auto* latency_track = track->add_latency_track(); latency_track->set_latency_name(latency_name); SetStat(GenerateStat(latency_values), latency_track->mutable_latency_stat()); } } // namespace LatencyMonitor::LatencyMonitor() : RecurrentRunner(FLAGS_latency_monitor_name, FLAGS_latency_monitor_interval) {} void LatencyMonitor::RunOnce(const double current_time) { static auto reader = MonitorManager::Instance()->CreateReader<LatencyRecordMap>( FLAGS_latency_recording_topic); reader->SetHistoryDepth(FLAGS_latency_reader_capacity); reader->Observe(); static std::string last_processed_key; std::string first_key_of_current_round; for (auto it = reader->Begin(); it != reader->End(); ++it) { const std::string current_key = absl::StrCat((*it)->module_name(), (*it)->header().sequence_num()); if (it == reader->Begin()) { first_key_of_current_round = current_key; } if (current_key == last_processed_key) { break; } UpdateStat(*it); } last_processed_key = first_key_of_current_round; if (current_time - flush_time_ > FLAGS_latency_report_interval) { flush_time_ = current_time; if (!track_map_.empty()) { PublishLatencyReport(); } } } void LatencyMonitor::UpdateStat( const std::shared_ptr<LatencyRecordMap>& records) { const auto module_name = records->module_name(); for (const auto& record : records->latency_records()) { track_map_[record.message_id()].emplace(record.begin_time(), record.end_time(), module_name); } if (!records->latency_records().empty()) { const auto begin_time = records->latency_records().begin()->begin_time(); const auto end_time = records->latency_records().rbegin()->end_time(); if (end_time > begin_time) { freq_map_[module_name] = records->latency_records().size() / apollo::cyber::Time(end_time - begin_time).ToSecond(); } } } void LatencyMonitor::PublishLatencyReport() { static auto writer = MonitorManager::Instance()->CreateWriter<LatencyReport>( FLAGS_latency_reporting_topic); apollo::common::util::FillHeader("LatencyReport", &latency_report_); AggregateLatency(); writer->Write(latency_report_); latency_report_.clear_header(); track_map_.clear(); latency_report_.clear_modules_latency(); latency_report_.clear_e2es_latency(); } void LatencyMonitor::AggregateLatency() { static const std::string kE2EStartPoint = FLAGS_pointcloud_topic; std::unordered_map<std::string, std::vector<uint64_t>> modules_track; std::unordered_map<std::string, std::vector<uint64_t>> e2es_track; std::unordered_set<std::string> all_modules; // Aggregate modules latencies std::string module_name; uint64_t begin_time = 0, end_time = 0; for (const auto& message : track_map_) { auto iter = message.second.begin(); while (iter != message.second.end()) { std::tie(begin_time, end_time, module_name) = *iter; modules_track[module_name].push_back(end_time - begin_time); all_modules.emplace(module_name); ++iter; } } // Aggregate E2E latencies std::unordered_map<std::string, uint64_t> e2e_latencies; for (const auto& message : track_map_) { uint64_t e2e_begin_time = 0; auto iter = message.second.begin(); e2e_latencies.clear(); while (iter != message.second.end()) { std::tie(begin_time, std::ignore, module_name) = *iter; if (e2e_begin_time == 0 && module_name == kE2EStartPoint) { e2e_begin_time = begin_time; } else if (module_name != kE2EStartPoint && e2e_begin_time != 0 && e2e_latencies.find(module_name) == e2e_latencies.end()) { const auto duration = begin_time - e2e_begin_time; e2e_latencies[module_name] = duration; e2es_track[module_name].push_back(duration); } ++iter; } } // The results could be in the following fromat: // e2e latency: // pointcloud -> perception: min(500), max(600), average(550), // sample_size(1500) pointcloud -> planning: min(800), max(1000), // average(900), sample_size(1500) pointcloud -> control: min(1200), // max(1300), average(1250), sample_size(1500) // ... // modules latency: // perception: min(5), max(50), average(30), sample_size(1000) // prediction: min(500), max(5000), average(2000), sample_size(800) // control: min(500), max(800), average(600), sample_size(800) // ... auto* modules_latency = latency_report_.mutable_modules_latency(); for (const auto& module : modules_track) { SetLatency(module.first, module.second, modules_latency); } auto* e2es_latency = latency_report_.mutable_e2es_latency(); for (const auto& e2e : e2es_track) { SetLatency(absl::StrCat(kE2EStartPoint, " -> ", e2e.first), e2e.second, e2es_latency); } } bool LatencyMonitor::GetFrequency(const std::string& channel_name, double* freq) { if (freq_map_.find(channel_name) == freq_map_.end()) { return false; } *freq = freq_map_[channel_name]; return true; } } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/software/localization_monitor.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. *****************************************************************************/ #pragma once #include "modules/monitor/common/recurrent_runner.h" namespace apollo { namespace monitor { class LocalizationMonitor : public RecurrentRunner { public: LocalizationMonitor(); void RunOnce(const double current_time) override; }; } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/software/summary_monitor.h
/****************************************************************************** * Copyright 2017 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. *****************************************************************************/ #pragma once #include <string> #include "modules/monitor/common/recurrent_runner.h" #include "modules/common_msgs/monitor_msgs/system_status.pb.h" namespace apollo { namespace monitor { // A monitor which summarize other monitors' result and publish the whole status // if it has changed. class SummaryMonitor : public RecurrentRunner { public: SummaryMonitor(); void RunOnce(const double current_time) override; // Escalate the status to a higher priority new status: // FATAL > ERROR > WARN > OK > UNKNOWN. static void EscalateStatus(const ComponentStatus::Status new_status, const std::string& message, ComponentStatus* current_status); private: size_t system_status_fp_ = 0; double last_broadcast_ = 0; }; } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/software/functional_safety_monitor.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. *****************************************************************************/ #pragma once #include "modules/monitor/common/recurrent_runner.h" #include "modules/common_msgs/monitor_msgs/system_status.pb.h" namespace apollo { namespace monitor { // Check if we need to switch to safe mode, and then // 1. Notify driver to take action. // 2. Trigger Guardian if no proper action was taken. class FunctionalSafetyMonitor : public RecurrentRunner { public: FunctionalSafetyMonitor(); void RunOnce(const double current_time); private: bool CheckSafety(); }; } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/software/process_monitor.cc
/****************************************************************************** * Copyright 2017 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 "modules/monitor/software/process_monitor.h" #include "gflags/gflags.h" #include "cyber/common/file.h" #include "cyber/common/log.h" #include "modules/common/util/map_util.h" #include "modules/monitor/common/monitor_manager.h" #include "modules/monitor/software/summary_monitor.h" DEFINE_string(process_monitor_name, "ProcessMonitor", "Name of the process monitor."); DEFINE_double(process_monitor_interval, 1.5, "Process status checking interval in seconds."); namespace apollo { namespace monitor { ProcessMonitor::ProcessMonitor() : RecurrentRunner(FLAGS_process_monitor_name, FLAGS_process_monitor_interval) {} void ProcessMonitor::RunOnce(const double current_time) { // Get running processes. std::vector<std::string> running_processes; for (const auto& cmd_file : cyber::common::Glob("/proc/*/cmdline")) { // Get process command string. std::string cmd_string; if (cyber::common::GetContent(cmd_file, &cmd_string) && !cmd_string.empty()) { // In /proc/<PID>/cmdline, the parts are separated with \0, which will be // converted back to whitespaces here. std::replace(cmd_string.begin(), cmd_string.end(), '\0', ' '); running_processes.push_back(cmd_string); } } auto manager = MonitorManager::Instance(); const auto& mode = manager->GetHMIMode(); // Check HMI modules. auto* hmi_modules = manager->GetStatus()->mutable_hmi_modules(); for (const auto& iter : mode.modules()) { const std::string& module_name = iter.first; const auto& config = iter.second.process_monitor_config(); UpdateStatus(running_processes, config, &hmi_modules->at(module_name)); } // Check monitored components. auto* components = manager->GetStatus()->mutable_components(); for (const auto& iter : mode.monitored_components()) { const std::string& name = iter.first; if (iter.second.has_process() && apollo::common::util::ContainsKey(*components, name)) { const auto& config = iter.second.process(); auto* status = components->at(name).mutable_process_status(); UpdateStatus(running_processes, config, status); } } // Check other components. auto* other_components = manager->GetStatus()->mutable_other_components(); for (const auto& iter : mode.other_components()) { const std::string& name = iter.first; const auto& config = iter.second; UpdateStatus(running_processes, config, &other_components->at(name)); } } void ProcessMonitor::UpdateStatus( const std::vector<std::string>& running_processes, const apollo::dreamview::ProcessMonitorConfig& config, ComponentStatus* status) { status->clear_status(); for (const std::string& command : running_processes) { bool all_keywords_matched = true; for (const std::string& keyword : config.command_keywords()) { if (command.find(keyword) == std::string::npos) { all_keywords_matched = false; break; } } if (all_keywords_matched) { // Process command keywords are all matched. The process is running. SummaryMonitor::EscalateStatus(ComponentStatus::OK, command, status); return; } } SummaryMonitor::EscalateStatus(ComponentStatus::FATAL, "", status); } } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/software/camera_monitor.cc
/****************************************************************************** * Copyright 2020 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 "modules/monitor/software/camera_monitor.h" #include <memory> #include <set> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "modules/common_msgs/sensor_msgs/sensor_image.pb.h" #include "cyber/common/log.h" #include "cyber/cyber.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/util/map_util.h" #include "modules/monitor/common/monitor_manager.h" #include "modules/monitor/software/summary_monitor.h" DEFINE_string(camera_monitor_name, "CameraMonitor", "Name of the camera monitor."); DEFINE_double(camera_monitor_interval, 5, "Camera monitor checking interval in seconds."); DEFINE_string(camera_component_name, "Camera", "Camera component name."); namespace apollo { namespace monitor { namespace { using ReaderAndMessagePair = std::pair<std::shared_ptr<cyber::ReaderBase>, std::shared_ptr<drivers::Image>>; ReaderAndMessagePair CreateReaderAndLatestsMessage(const std::string& camera) { const auto reader = MonitorManager::Instance()->CreateReader<drivers::Image>(camera); reader->Observe(); const auto message = reader->GetLatestObserved(); reader->ClearData(); return {reader, message}; } static const auto camera_topic_set = std::set<std::string>{ FLAGS_image_long_topic, FLAGS_camera_image_long_topic, FLAGS_camera_image_short_topic, FLAGS_camera_front_6mm_topic, FLAGS_camera_front_6mm_2_topic, FLAGS_camera_front_12mm_topic, // Add more cameras here if you want to monitor. }; } // namespace CameraMonitor::CameraMonitor() : RecurrentRunner(FLAGS_camera_monitor_name, FLAGS_camera_monitor_interval) {} void CameraMonitor::RunOnce(const double current_time) { auto* manager = MonitorManager::Instance(); auto* component = apollo::common::util::FindOrNull( *manager->GetStatus()->mutable_components(), FLAGS_camera_component_name); if (component == nullptr) { // camera is not monitored in current mode, skip. return; } auto* status = component->mutable_other_status(); UpdateStatus(status); } void CameraMonitor::UpdateStatus(ComponentStatus* status) { status->clear_status(); std::string frame_id = ""; for (const auto& topic : camera_topic_set) { const auto& reader_message_pair = CreateReaderAndLatestsMessage(topic); const auto& reader = reader_message_pair.first; const auto& message = reader_message_pair.second; if (reader != nullptr && message != nullptr) { if (frame_id.empty()) { const auto& header = message->header(); if (header.has_frame_id()) { frame_id = header.frame_id(); } } else { SummaryMonitor::EscalateStatus( ComponentStatus::ERROR, absl::StrCat("Only one camera is permitted"), status); } } } if (frame_id.empty()) { SummaryMonitor::EscalateStatus( ComponentStatus::ERROR, absl::StrCat("No camera is detected"), status); } else { SummaryMonitor::EscalateStatus( ComponentStatus::OK, absl::StrCat("Detected one camera: ", frame_id), status); } } } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/software/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) MONITOR_COPTS = ['-DMODULE_NAME=\\"monitor\\"'] cc_library( name = "process_monitor", srcs = ["process_monitor.cc"], hdrs = ["process_monitor.h"], copts = MONITOR_COPTS, deps = [ ":summary_monitor", "//modules/dreamview/proto:hmi_mode_cc_proto", "//modules/monitor/common:monitor_manager", "//modules/monitor/common:recurrent_runner", "@com_github_gflags_gflags//:gflags", ], ) cc_library( name = "module_monitor", srcs = ["module_monitor.cc"], hdrs = ["module_monitor.h"], copts = MONITOR_COPTS, deps = [ ":summary_monitor", "//cyber", "//modules/dreamview/proto:hmi_mode_cc_proto", "//modules/monitor/common:monitor_manager", "//modules/monitor/common:recurrent_runner", "@com_google_absl//:absl", ], ) cc_library( name = "camera_monitor", srcs = ["camera_monitor.cc"], hdrs = ["camera_monitor.h"], copts = MONITOR_COPTS, deps = [ ":summary_monitor", "//cyber", "//modules/dreamview/proto:hmi_mode_cc_proto", "//modules/common_msgs/sensor_msgs:sensor_image_cc_proto", "//modules/monitor/common:monitor_manager", "//modules/monitor/common:recurrent_runner", "@com_google_absl//:absl", ], ) cc_library( name = "channel_monitor", srcs = ["channel_monitor.cc"], hdrs = ["channel_monitor.h"], copts = MONITOR_COPTS, deps = [ ":latency_monitor", ":summary_monitor", "//modules/common/latency_recorder/proto:latency_record_cc_proto", "//modules/common_msgs/chassis_msgs:chassis_detail_cc_proto", "//modules/common_msgs/control_msgs:control_cmd_cc_proto", "//modules/dreamview/proto:hmi_mode_cc_proto", "//modules/common_msgs/sensor_msgs:conti_radar_cc_proto", "//modules/common_msgs/sensor_msgs:pointcloud_cc_proto", "//modules/common_msgs/localization_msgs:pose_cc_proto", "//modules/common_msgs/planning_msgs:navigation_cc_proto", "//modules/monitor/common:monitor_manager", "//modules/monitor/common:recurrent_runner", "//modules/common_msgs/perception_msgs:perception_obstacle_cc_proto", "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/common_msgs/prediction_msgs:prediction_obstacle_cc_proto", "@com_google_absl//:absl", ], ) cc_library( name = "localization_monitor", srcs = ["localization_monitor.cc"], hdrs = ["localization_monitor.h"], copts = MONITOR_COPTS, deps = [ ":summary_monitor", "//modules/common/adapters:adapter_gflags", "//modules/common_msgs/localization_msgs:localization_cc_proto", "//modules/monitor/common:monitor_manager", "//modules/monitor/common:recurrent_runner", ], ) cc_library( name = "functional_safety_monitor", srcs = ["functional_safety_monitor.cc"], hdrs = ["functional_safety_monitor.h"], copts = MONITOR_COPTS, deps = [ "//modules/monitor/common:monitor_manager", "//modules/monitor/common:recurrent_runner", ], ) cc_library( name = "summary_monitor", srcs = ["summary_monitor.cc"], hdrs = ["summary_monitor.h"], copts = MONITOR_COPTS, deps = [ "//modules/common/adapters:adapter_gflags", "//modules/monitor/common:monitor_manager", "//modules/monitor/common:recurrent_runner", "@com_google_absl//:absl", ], ) cc_library( name = "recorder_monitor", srcs = ["recorder_monitor.cc"], hdrs = ["recorder_monitor.h"], copts = MONITOR_COPTS, deps = [ ":summary_monitor", "//modules/common/adapters:adapter_gflags", "//modules/common_msgs/monitor_msgs:smart_recorder_status_cc_proto", "//modules/monitor/common:monitor_manager", "//modules/monitor/common:recurrent_runner", ], ) cc_library( name = "latency_monitor", srcs = ["latency_monitor.cc"], hdrs = ["latency_monitor.h"], copts = MONITOR_COPTS, deps = [ ":summary_monitor", "//modules/common/adapters:adapter_gflags", "//modules/common/latency_recorder/proto:latency_record_cc_proto", "//modules/monitor/common:monitor_manager", "//modules/monitor/common:recurrent_runner", ], ) cpplint()
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/software/localization_monitor.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 "modules/monitor/software/localization_monitor.h" #include "cyber/common/log.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/util/map_util.h" #include "modules/common_msgs/localization_msgs/localization.pb.h" #include "modules/monitor/common/monitor_manager.h" #include "modules/monitor/software/summary_monitor.h" DEFINE_string(localization_monitor_name, "LocalizationMonitor", "Name of the localization monitor."); DEFINE_double(localization_monitor_interval, 5, "Localization status checking interval (s)."); DEFINE_string(localization_component_name, "Localization", "Localization component name."); namespace apollo { namespace monitor { using apollo::localization::LocalizationStatus; using apollo::localization::MeasureState; LocalizationMonitor::LocalizationMonitor() : RecurrentRunner(FLAGS_localization_monitor_name, FLAGS_localization_monitor_interval) {} void LocalizationMonitor::RunOnce(const double current_time) { auto manager = MonitorManager::Instance(); auto* component = apollo::common::util::FindOrNull( *manager->GetStatus()->mutable_components(), FLAGS_localization_component_name); if (component == nullptr) { // localization is not monitored in current mode, skip. return; } static auto reader = manager->CreateReader<LocalizationStatus>(FLAGS_localization_msf_status); reader->Observe(); const auto status = reader->GetLatestObserved(); ComponentStatus* component_status = component->mutable_other_status(); component_status->clear_status(); if (status == nullptr) { SummaryMonitor::EscalateStatus(ComponentStatus::ERROR, "No LocalizationStatus received", component_status); return; } // Translate LocalizationStatus to ComponentStatus. Note that ERROR and FATAL // will trigger safety mode in current settings. switch (status->fusion_status()) { case MeasureState::OK: SummaryMonitor::EscalateStatus(ComponentStatus::OK, "", component_status); break; case MeasureState::WARNNING: SummaryMonitor::EscalateStatus( ComponentStatus::WARN, absl::StrCat("WARNNING: ", status->state_message()), component_status); break; case MeasureState::ERROR: SummaryMonitor::EscalateStatus( ComponentStatus::WARN, absl::StrCat("ERROR: ", status->state_message()), component_status); break; case MeasureState::CRITICAL_ERROR: SummaryMonitor::EscalateStatus( ComponentStatus::ERROR, absl::StrCat("CRITICAL_ERROR: ", status->state_message()), component_status); break; case MeasureState::FATAL_ERROR: SummaryMonitor::EscalateStatus( ComponentStatus::FATAL, absl::StrCat("FATAL_ERROR: ", status->state_message()), component_status); break; default: AFATAL << "Unknown fusion_status: " << status->fusion_status(); break; } } } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/software/recorder_monitor.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 "modules/monitor/software/recorder_monitor.h" #include "cyber/common/log.h" #include "modules/common_msgs/monitor_msgs/smart_recorder_status.pb.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/util/map_util.h" #include "modules/monitor/common/monitor_manager.h" #include "modules/monitor/software/summary_monitor.h" DEFINE_string(smart_recorder_monitor_name, "SmartRecorderMonitor", "Name of the smart recorder monitor."); DEFINE_double(smart_recorder_monitor_interval, 5, "Smart recorder status checking interval (s)."); DEFINE_string(smart_recorder_component_name, "SmartRecorder", "Smart recorder component name."); namespace apollo { namespace monitor { using apollo::data::RecordingState; using apollo::data::SmartRecorderStatus; RecorderMonitor::RecorderMonitor() : RecurrentRunner(FLAGS_smart_recorder_monitor_name, FLAGS_smart_recorder_monitor_interval) {} void RecorderMonitor::RunOnce(const double current_time) { auto manager = MonitorManager::Instance(); auto* component = apollo::common::util::FindOrNull( *manager->GetStatus()->mutable_components(), FLAGS_smart_recorder_component_name); if (component == nullptr) { // SmartRecorder is not monitored in current mode, skip. return; } static auto reader = manager->CreateReader<SmartRecorderStatus>(FLAGS_recorder_status_topic); reader->Observe(); const auto status = reader->GetLatestObserved(); ComponentStatus* component_status = component->mutable_other_status(); component_status->clear_status(); if (status == nullptr) { SummaryMonitor::EscalateStatus(ComponentStatus::ERROR, "No SmartRecorderStatus received", component_status); return; } // Translate SmartRecorderStatus to ComponentStatus. Note that ERROR and FATAL // will trigger safety mode in current settings. switch (status->recording_state()) { case RecordingState::RECORDING: SummaryMonitor::EscalateStatus(ComponentStatus::OK, "", component_status); break; case RecordingState::TERMINATING: SummaryMonitor::EscalateStatus( ComponentStatus::WARN, absl::StrCat("WARNNING: ", status->state_message()), component_status); break; case RecordingState::STOPPED: SummaryMonitor::EscalateStatus( ComponentStatus::OK, absl::StrCat("STOPPED: ", status->state_message()), component_status); break; default: AFATAL << "Unknown recording status: " << status->recording_state(); break; } } } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/software/channel_monitor.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 "modules/monitor/software/channel_monitor.h" #include <memory> #include <string> #include <utility> #include <vector> #include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" #include "google/protobuf/compiler/parser.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/dynamic_message.h" #include "modules/common_msgs/chassis_msgs/chassis_detail.pb.h" #include "modules/common/latency_recorder/proto/latency_record.pb.h" #include "modules/common_msgs/control_msgs/control_cmd.pb.h" #include "modules/common_msgs/sensor_msgs/conti_radar.pb.h" #include "modules/common_msgs/sensor_msgs/pointcloud.pb.h" #include "modules/common_msgs/localization_msgs/pose.pb.h" #include "modules/common_msgs/planning_msgs/navigation.pb.h" #include "modules/common_msgs/perception_msgs/perception_obstacle.pb.h" #include "modules/common_msgs/planning_msgs/planning.pb.h" #include "modules/common_msgs/prediction_msgs/prediction_obstacle.pb.h" #include "cyber/common/log.h" #include "cyber/cyber.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/util/map_util.h" #include "modules/monitor/common/monitor_manager.h" #include "modules/monitor/software/summary_monitor.h" DEFINE_string(channel_monitor_name, "ChannelMonitor", "Name of the channel monitor."); DEFINE_double(channel_monitor_interval, 5, "Channel monitor checking interval in seconds."); namespace apollo { namespace monitor { namespace { using ReaderAndMessagePair = std::pair<std::shared_ptr<cyber::ReaderBase>, std::shared_ptr<google::protobuf::Message>>; template <typename T> ReaderAndMessagePair CreateReaderAndLatestsMessage(const std::string& channel) { const auto reader = MonitorManager::Instance()->CreateReader<T>(channel); reader->Observe(); const auto message = reader->GetLatestObserved(); return {reader, message}; } // We have to specify exact type of each channel. This function is a wrapper for // those only need a ReaderBase. ReaderAndMessagePair GetReaderAndLatestMessage(const std::string& channel) { static const auto channel_function_map = std::unordered_map<std::string, std::function<ReaderAndMessagePair( const std::string& channel)>>{ {FLAGS_control_command_topic, &CreateReaderAndLatestsMessage<control::ControlCommand>}, {FLAGS_localization_topic, &CreateReaderAndLatestsMessage<localization::LocalizationEstimate>}, {FLAGS_perception_obstacle_topic, &CreateReaderAndLatestsMessage<perception::PerceptionObstacles>}, {FLAGS_prediction_topic, &CreateReaderAndLatestsMessage<prediction::PredictionObstacles>}, {FLAGS_planning_trajectory_topic, &CreateReaderAndLatestsMessage<planning::ADCTrajectory>}, {FLAGS_conti_radar_topic, &CreateReaderAndLatestsMessage<drivers::ContiRadar>}, {FLAGS_relative_map_topic, &CreateReaderAndLatestsMessage<relative_map::MapMsg>}, {FLAGS_pointcloud_topic, &CreateReaderAndLatestsMessage<drivers::PointCloud>}, {FLAGS_pointcloud_16_topic, &CreateReaderAndLatestsMessage<drivers::PointCloud>}, {FLAGS_pointcloud_16_raw_topic, &CreateReaderAndLatestsMessage<drivers::PointCloud>}, {FLAGS_pointcloud_128_topic, &CreateReaderAndLatestsMessage<drivers::PointCloud>}, {FLAGS_pointcloud_16_front_up_topic, &CreateReaderAndLatestsMessage<drivers::PointCloud>}, {FLAGS_chassis_detail_topic, &CreateReaderAndLatestsMessage<canbus::ChassisDetail>}, {FLAGS_pointcloud_hesai_40p_topic, &CreateReaderAndLatestsMessage<drivers::PointCloud>} // Add more channels here if you want to monitor. }; auto entry = channel_function_map.find(channel); if (entry != channel_function_map.end()) { return (entry->second)(channel); } AERROR << "Channel is not handled by ChannelMonitor: " << channel; return {nullptr, nullptr}; } bool ValidateFields(const google::protobuf::Message& message, const std::vector<std::string>& fields, const size_t field_step) { if (field_step >= fields.size()) { return true; } const auto* desc = message.GetDescriptor(); const auto* refl = message.GetReflection(); const auto field_count = desc->field_count(); for (int field_idx = 0; field_idx < field_count; ++field_idx) { const auto* field_desc = desc->field(field_idx); if (field_desc->name() == fields[field_step]) { if (field_desc->is_repeated()) { // For repeated field, we do not expect it has deeper level validation const auto size = refl->FieldSize(message, field_desc); return size > 0 && field_step == fields.size() - 1; } if (field_desc->type() != google::protobuf::FieldDescriptor::TYPE_MESSAGE) { return refl->HasField(message, field_desc) && field_step == fields.size() - 1; } return ValidateFields(refl->GetMessage(message, field_desc), fields, field_step + 1); } } return false; } } // namespace ChannelMonitor::ChannelMonitor( const std::shared_ptr<LatencyMonitor>& latency_monitor) : RecurrentRunner(FLAGS_channel_monitor_name, FLAGS_channel_monitor_interval), latency_monitor_(latency_monitor) {} void ChannelMonitor::RunOnce(const double current_time) { auto manager = MonitorManager::Instance(); const auto& mode = manager->GetHMIMode(); auto* components = manager->GetStatus()->mutable_components(); for (const auto& iter : mode.monitored_components()) { const std::string& name = iter.first; const auto& config = iter.second; if (config.has_channel()) { double freq; const auto update_freq = latency_monitor_->GetFrequency(config.channel().name(), &freq); UpdateStatus(config.channel(), components->at(name).mutable_channel_status(), update_freq, freq); } } } void ChannelMonitor::UpdateStatus( const apollo::dreamview::ChannelMonitorConfig& config, ComponentStatus* status, const bool update_freq, const double freq) { status->clear_status(); const auto reader_message_pair = GetReaderAndLatestMessage(config.name()); const auto reader = reader_message_pair.first; const auto message = reader_message_pair.second; if (reader == nullptr) { SummaryMonitor::EscalateStatus( ComponentStatus::UNKNOWN, absl::StrCat(config.name(), " is not registered in ChannelMonitor."), status); return; } if (message == nullptr || message->ByteSize() == 0) { SummaryMonitor::EscalateStatus( ComponentStatus::FATAL, absl::StrCat("the message ", config.name(), " reseived is empty."), status); return; } // Check channel delay const double delay = reader->GetDelaySec(); if (delay < 0 || delay > config.delay_fatal()) { SummaryMonitor::EscalateStatus( ComponentStatus::FATAL, absl::StrCat(config.name(), " delayed for ", delay, " seconds."), status); } // Check channel fields const std::string field_sepr = "."; if (message != nullptr) { for (const auto& field : config.mandatory_fields()) { if (!ValidateFields(*message, absl::StrSplit(field, field_sepr), 0)) { SummaryMonitor::EscalateStatus( ComponentStatus::ERROR, absl::StrCat(config.name(), " missing field ", field), status); } } } // Check channel frequency if (update_freq) { if (freq > config.max_frequency_allowed()) { SummaryMonitor::EscalateStatus( ComponentStatus::WARN, absl::StrCat(config.name(), " has frequency ", freq, " > max allowed ", config.max_frequency_allowed()), status); } if (freq < config.min_frequency_allowed()) { SummaryMonitor::EscalateStatus( ComponentStatus::WARN, absl::StrCat(config.name(), " has frequency ", freq, " < min allowed ", config.max_frequency_allowed()), status); } } SummaryMonitor::EscalateStatus(ComponentStatus::OK, "", status); } } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/software/channel_monitor.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. *****************************************************************************/ #pragma once #include <memory> #include <string> #include <unordered_map> #include "modules/dreamview/proto/hmi_mode.pb.h" #include "modules/monitor/common/recurrent_runner.h" #include "modules/common_msgs/monitor_msgs/system_status.pb.h" #include "modules/monitor/software/latency_monitor.h" namespace apollo { namespace monitor { class ChannelMonitor : public RecurrentRunner { public: explicit ChannelMonitor( const std::shared_ptr<LatencyMonitor>& latency_monitor); void RunOnce(const double current_time) override; private: static void UpdateStatus( const apollo::dreamview::ChannelMonitorConfig& config, ComponentStatus* status, const bool update_freq, const double freq); std::shared_ptr<LatencyMonitor> latency_monitor_; }; } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/software/process_monitor.h
/****************************************************************************** * Copyright 2017 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. *****************************************************************************/ #pragma once #include <string> #include <vector> #include "modules/dreamview/proto/hmi_mode.pb.h" #include "modules/common_msgs/monitor_msgs/system_status.pb.h" #include "modules/monitor/common/recurrent_runner.h" namespace apollo { namespace monitor { class ProcessMonitor : public RecurrentRunner { public: ProcessMonitor(); void RunOnce(const double current_time) override; private: static void UpdateStatus( const std::vector<std::string>& running_processes, const apollo::dreamview::ProcessMonitorConfig& config, ComponentStatus* status); }; } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/software/camera_monitor.h
/****************************************************************************** * Copyright 2020 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. *****************************************************************************/ #pragma once #include "modules/monitor/common/recurrent_runner.h" #include "modules/common_msgs/monitor_msgs/system_status.pb.h" namespace apollo { namespace monitor { class CameraMonitor : public RecurrentRunner { public: CameraMonitor(); void RunOnce(const double current_time) override; private: static void UpdateStatus(ComponentStatus* status); }; } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/software/module_monitor.h
/****************************************************************************** * Copyright 2020 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. *****************************************************************************/ #pragma once #include <memory> #include <string> #include <vector> #include "cyber/service_discovery/specific_manager/node_manager.h" #include "modules/dreamview/proto/hmi_mode.pb.h" #include "modules/monitor/common/recurrent_runner.h" #include "modules/common_msgs/monitor_msgs/system_status.pb.h" namespace apollo { namespace monitor { class ModuleMonitor : public RecurrentRunner { public: using NodeManagerPtr = std::shared_ptr<cyber::service_discovery::NodeManager>; ModuleMonitor(); void RunOnce(const double current_time) override; void UpdateStatus(const apollo::dreamview::ModuleMonitorConfig& config, const std::string& module_name, ComponentStatus* status); private: NodeManagerPtr node_manager_ = nullptr; }; } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/common/recurrent_runner_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 "modules/monitor/common/recurrent_runner.h" #include "cyber/common/log.h" #include "gtest/gtest.h" namespace apollo { namespace monitor { class DummyRecurrentRunner : public RecurrentRunner { public: explicit DummyRecurrentRunner(const double interval) : RecurrentRunner("DummyRecurrentRunner", interval) {} void RunOnce(const double current_time) override {} inline unsigned int GetRoundCount() { return round_count_; } }; TEST(RecurrentRunnerTest, Tick) { DummyRecurrentRunner runner(1); EXPECT_EQ(0, runner.GetRoundCount()); runner.Tick(0.1); // Triggered. Next trigger time: 1.1 EXPECT_EQ(1, runner.GetRoundCount()); runner.Tick(1.0); // Skipped. Next trigger time: 1.1 EXPECT_EQ(1, runner.GetRoundCount()); runner.Tick(2); // Triggered. Next trigger time: 3 runner.Tick(2.9); // Not triggered. Next trigger time: 3 runner.Tick(9); // Triggered. Next trigger time: 10 EXPECT_EQ(3, runner.GetRoundCount()); } } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/common/recurrent_runner.h
/****************************************************************************** * Copyright 2017 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. *****************************************************************************/ #pragma once #include <string> /** * @namespace apollo::monitor * @brief apollo::monitor */ namespace apollo { namespace monitor { class RecurrentRunner { public: RecurrentRunner(const std::string &name, const double interval); virtual ~RecurrentRunner() = default; // Tick once, which may or may not execute the RunOnce() function, based on // the interval setting. void Tick(const double current_time); // Do the actual work. virtual void RunOnce(const double current_time) = 0; protected: std::string name_; unsigned int round_count_ = 0; private: double interval_; double next_round_ = 0; }; } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/common/monitor_manager.h
/****************************************************************************** * Copyright 2017 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. *****************************************************************************/ #pragma once #include <memory> #include <string> #include <unordered_map> #include "cyber/common/macros.h" #include "modules/common/monitor_log/monitor_log_buffer.h" #include "modules/dreamview/proto/hmi_config.pb.h" #include "modules/dreamview/proto/hmi_mode.pb.h" #include "modules/common_msgs/dreamview_msgs/hmi_status.pb.h" #include "modules/common_msgs/monitor_msgs/system_status.pb.h" /** * @namespace apollo::monitor * @brief apollo::monitor */ namespace apollo { namespace monitor { // Centralized monitor config and status manager. class MonitorManager { public: void Init(const std::shared_ptr<apollo::cyber::Node>& node); // Start and end a monitoring frame. bool StartFrame(const double current_time); void EndFrame(); // Getters. const apollo::dreamview::HMIMode& GetHMIMode() const { return mode_config_; } bool IsInAutonomousMode() const { return in_autonomous_driving_; } SystemStatus* GetStatus() { return &status_; } apollo::common::monitor::MonitorLogBuffer& LogBuffer() { return log_buffer_; } // Cyber reader / writer creator. template <class T> std::shared_ptr<cyber::Reader<T>> CreateReader(const std::string& channel) { if (readers_.find(channel) == readers_.end()) { readers_.emplace(channel, node_->CreateReader<T>(channel)); } return std::dynamic_pointer_cast<cyber::Reader<T>>(readers_[channel]); } template <class T> std::shared_ptr<cyber::Writer<T>> CreateWriter(const std::string& channel) { return node_->CreateWriter<T>(channel); } private: SystemStatus status_; // Input statuses. std::string current_mode_; const apollo::dreamview::HMIConfig hmi_config_; apollo::dreamview::HMIMode mode_config_; bool in_autonomous_driving_ = false; bool CheckAutonomousDriving(const double current_time); apollo::common::monitor::MonitorLogBuffer log_buffer_; std::shared_ptr<apollo::cyber::Node> node_; std::unordered_map<std::string, std::shared_ptr<cyber::ReaderBase>> readers_; DECLARE_SINGLETON(MonitorManager) }; } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/common/recurrent_runner.cc
/****************************************************************************** * Copyright 2017 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 "modules/monitor/common/recurrent_runner.h" #include "cyber/common/log.h" namespace apollo { namespace monitor { RecurrentRunner::RecurrentRunner(const std::string &name, const double interval) : name_(name), interval_(interval) {} void RecurrentRunner::Tick(const double current_time) { if (next_round_ <= current_time) { ++round_count_; AINFO_EVERY(100) << name_ << " is running round #" << round_count_; next_round_ = current_time + interval_; RunOnce(current_time); } } } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/common/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) MONITOR_COPTS = ['-DMODULE_NAME=\\"monitor\\"'] cc_library( name = "recurrent_runner", srcs = ["recurrent_runner.cc"], hdrs = ["recurrent_runner.h"], copts = MONITOR_COPTS, deps = [ "//cyber", ], ) cc_test( name = "recurrent_runner_test", size = "small", srcs = ["recurrent_runner_test.cc"], copts = MONITOR_COPTS, deps = [ ":recurrent_runner", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cc_library( name = "monitor_manager", srcs = ["monitor_manager.cc"], hdrs = ["monitor_manager.h"], copts = MONITOR_COPTS, deps = [ "//cyber", "//modules/common_msgs/chassis_msgs:chassis_cc_proto", "//modules/common/adapters:adapter_gflags", "//modules/common/monitor_log", "//modules/common_msgs/basic_msgs:drive_event_cc_proto", "//modules/common/util", "//modules/common/util:util_tool", "//modules/dreamview/backend/common:dreamview_gflags", "//modules/dreamview/backend/hmi:hmi_worker", "//modules/dreamview/proto:hmi_config_cc_proto", "//modules/dreamview/proto:hmi_mode_cc_proto", "//modules/common_msgs/dreamview_msgs:hmi_status_cc_proto", "//modules/common_msgs/localization_msgs:pose_cc_proto", "//modules/common_msgs/monitor_msgs:system_status_cc_proto", "@com_github_gflags_gflags//:gflags", ], ) cpplint()
0
apollo_public_repos/apollo/modules/monitor
apollo_public_repos/apollo/modules/monitor/common/monitor_manager.cc
/****************************************************************************** * Copyright 2017 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 "modules/monitor/common/monitor_manager.h" #include "gflags/gflags.h" #include "modules/common_msgs/chassis_msgs/chassis.pb.h" #include "cyber/common/file.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/configs/config_gflags.h" #include "modules/common/util/map_util.h" #include "modules/dreamview/backend/common/dreamview_gflags.h" #include "modules/dreamview/backend/hmi/hmi_worker.h" namespace apollo { namespace monitor { using apollo::canbus::Chassis; using apollo::dreamview::HMIWorker; MonitorManager::MonitorManager() : hmi_config_(HMIWorker::LoadConfig()), log_buffer_(apollo::common::monitor::MonitorMessageItem::MONITOR) {} void MonitorManager::Init(const std::shared_ptr<apollo::cyber::Node>& node) { node_ = node; if (FLAGS_use_sim_time) { status_.set_is_realtime_in_simulation(true); } } bool MonitorManager::StartFrame(const double current_time) { // Get latest HMIStatus. static auto hmi_status_reader = CreateReader<apollo::dreamview::HMIStatus>(FLAGS_hmi_status_topic); hmi_status_reader->Observe(); const auto hmi_status = hmi_status_reader->GetLatestObserved(); if (hmi_status == nullptr) { AERROR << "No HMIStatus was received."; return false; } if (current_mode_ != hmi_status->current_mode()) { // Mode changed, update configs and monitored. current_mode_ = hmi_status->current_mode(); mode_config_ = HMIWorker::LoadMode(hmi_config_.modes().at(current_mode_)); status_.clear_hmi_modules(); for (const auto& iter : mode_config_.modules()) { status_.mutable_hmi_modules()->insert({iter.first, {}}); } status_.clear_components(); for (const auto& iter : mode_config_.monitored_components()) { status_.mutable_components()->insert({iter.first, {}}); } status_.clear_other_components(); for (const auto& iter : mode_config_.other_components()) { status_.mutable_other_components()->insert({iter.first, {}}); } } else { // Mode not changed, clear component summary from the last frame. for (auto& iter : *status_.mutable_components()) { iter.second.clear_summary(); } } in_autonomous_driving_ = CheckAutonomousDriving(current_time); return true; } void MonitorManager::EndFrame() { // Print and publish all monitor logs. log_buffer_.Publish(); } bool MonitorManager::CheckAutonomousDriving(const double current_time) { // It's in offline mode if use_sim_time is set. if (FLAGS_use_sim_time) { return false; } // Get current DrivingMode, which will affect how we monitor modules. static auto chassis_reader = CreateReader<Chassis>(FLAGS_chassis_topic); chassis_reader->Observe(); const auto chassis = chassis_reader->GetLatestObserved(); if (chassis == nullptr) { return false; } // If SimControl is used, return false to ignore safety check. if (chassis->header().module_name() == "SimControl") { return false; } // Ignore old messages which are likely from playback. const double msg_time = chassis->header().timestamp_sec(); if (msg_time + FLAGS_system_status_lifetime_seconds < current_time) { return false; } return chassis->driving_mode() == Chassis::COMPLETE_AUTO_DRIVE; } } // namespace monitor } // namespace apollo
0
apollo_public_repos/apollo/modules
apollo_public_repos/apollo/modules/drivers/drivers.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") cc_library( name = "drivers", includes = ["include"], hdrs = glob(["include/**/*.h"]), srcs = glob(["lib/*.so*"], exclude=["lib/libsmartereye_component.so"]), include_prefix = "modules/drivers", strip_include_prefix = "include", visibility = ["//visibility:public"], )
0
apollo_public_repos/apollo/modules
apollo_public_repos/apollo/modules/drivers/cyberfile.xml
<package format="2"> <name>drivers</name> <version>local</version> <description> Apollo drivers module. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <depend type="binary" repo_name="cyber">cyber-dev</depend> <depend type="binary" repo_name="common" lib_names="common">common-dev</depend> <depend repo_name="common-msgs" lib_names="common-msgs">common-msgs-dev</depend> <depend type="binary" repo_name="transform" lib_names="transform">transform-dev</depend> <depend repo_name="com_github_gflags_gflags" lib_names="gflags">3rd-gflags-dev</depend> <depend repo_name="com_google_googletest" lib_names="gtest,gtest_main">3rd-gtest-dev</depend> <depend repo_name="proj">3rd-proj-dev</depend> <depend repo_name="eigen">3rd-eigen3-dev</depend> <depend repo_name="com_google_absl" lib_names="absl">3rd-absl-dev</depend> <depend repo_name="com_github_jbeder_yaml_cpp" lib_names="yaml-cpp">3rd-yaml-cpp-dev</depend> <depend repo_name="boost">3rd-boost-dev</depend> <depend repo_name="opencv" lib_names="core,highgui,imgproc,imgcodecs">3rd-opencv-dev</depend> <depend repo_name="can_card_library" lib_names="hermes_can" type="binary">3rd-can-card-library-dev</depend> <depend repo_name="camera_library_dev" lib_names="smartereye" type="binary">3rd-camera-library-dev</depend> <depend repo_name="rtklib" lib_names="rtklib" type="binary">3rd-rtklib-dev</depend> <depend repo_name="portaudio">3rd-portaudio-dev</depend> <depend repo_name="ffmpeg" lib_names="avcodec,avformat,swscale,avutil">3rd-ffmpeg-dev</depend> <depend repo_name="adv_plat" lib_names="adv_plat">3rd-adv-plat-dev</depend> <depend expose="False">3rd-pcl-dev</depend> <depend>libpcap-dev</depend> <depend>bazel-extend-tools-dev</depend> <depend expose="False">3rd-rules-python-dev</depend> <depend expose="False">3rd-grpc-dev</depend> <depend expose="False">3rd-bazel-skylib-dev</depend> <depend expose="False">3rd-rules-proto-dev</depend> <depend expose="False">3rd-py-dev</depend> <type>module</type> <src_path url="https://github.com/ApolloAuto/apollo">//modules/drivers</src_path> </package>
0
apollo_public_repos/apollo/modules
apollo_public_repos/apollo/modules/drivers/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) install( name = "install", data_dest = "drivers", data = [ ":cyberfile.xml", ":drivers.BUILD", ], deps = [ ":pb_drivers", ":pb_hdrs", "//modules/drivers/canbus:install", "//modules/drivers/camera:install", "//modules/drivers/gnss:install", "//modules/drivers/lidar:install", "//modules/drivers/microphone:install", "//modules/drivers/radar:install", "//modules/drivers/smartereye:install", "//modules/drivers/tools/image_decompress:install", "//modules/drivers/video:install", "//modules/drivers/canbus/can_client:install", "//modules/drivers/canbus/common:install", "//modules/drivers/gnss/test:install", "//modules/drivers/lidar/hesai:install", "//modules/drivers/lidar/robosense:install", "//modules/drivers/lidar/velodyne/compensator:install", "//modules/drivers/lidar/velodyne/driver:install", "//modules/drivers/lidar/velodyne/fusion:install", "//modules/drivers/lidar/velodyne/parser:install", "//modules/drivers/lidar/velodyne:install", "//modules/drivers/radar/conti_radar:install", "//modules/drivers/radar/racobit_radar:install", "//modules/drivers/radar/ultrasonic_radar:install", "//modules/drivers/video/tools/decode_video:install", ":pb_drivers_py" ], ) install_files( name = "pb_drivers", dest = "drivers", files = [ "//modules/common_msgs/sensor_msgs:ins_py_pb2", "//modules/common_msgs/sensor_msgs:conti_radar_py_pb2", "//modules/common_msgs/sensor_msgs:pointcloud_py_pb2", "//modules/common_msgs/sensor_msgs:sensor_image_py_pb2", "//modules/drivers/radar/conti_radar/proto:conti_radar_conf_py_pb2", ], ) install( name = "pb_hdrs", data_dest = "drivers/include", data = [ "//modules/drivers/camera/proto:config_cc_proto", "//modules/drivers/canbus/proto:sensor_canbus_conf_py_pb2", "//modules/drivers/gnss/proto:config_cc_proto", "//modules/drivers/gnss/proto:gnss_status_cc_proto", "//modules/drivers/lidar/proto:config_cc_proto", "//modules/drivers/lidar/proto:hesai_config_cc_proto", "//modules/drivers/lidar/proto:hesai_cc_proto", "//modules/drivers/lidar/proto:lidar_parameter_cc_proto", "//modules/drivers/lidar/proto:robosense_config_cc_proto", "//modules/drivers/lidar/proto:robosense_cc_proto", "//modules/drivers/lidar/proto:velodyne_config_cc_proto", "//modules/drivers/lidar/proto:velodyne_cc_proto", "//modules/drivers/microphone/proto:audio_cc_proto", "//modules/drivers/microphone/proto:microphone_config_cc_proto", "//modules/drivers/radar/conti_radar/proto:conti_radar_conf_cc_proto", "//modules/drivers/radar/racobit_radar/proto:racobit_radar_conf_cc_proto", "//modules/drivers/radar/ultrasonic_radar/proto:ultrasonic_radar_conf_cc_proto", "//modules/drivers/smartereye/proto:config_cc_proto", "//modules/drivers/tools/image_decompress/proto:config_cc_proto", "//modules/drivers/video/proto:video_h265cfg_cc_proto", ], ) install_files( name = "pb_drivers_py", dest = "drivers/python/modules/drivers", files = [ "//modules/drivers/camera/proto:config_py_pb2", "//modules/drivers/canbus/proto:sensor_canbus_conf_py_pb2", "//modules/drivers/gnss/proto:config_py_pb2", "//modules/drivers/gnss/proto:gnss_status_py_pb2", "//modules/drivers/lidar/proto:config_py_pb2", "//modules/drivers/lidar/proto:hesai_config_py_pb2", "//modules/drivers/lidar/proto:hesai_py_pb2", "//modules/drivers/lidar/proto:lidar_parameter_py_pb2", "//modules/drivers/lidar/proto:robosense_config_py_pb2", "//modules/drivers/lidar/proto:robosense_py_pb2", "//modules/drivers/lidar/proto:velodyne_py_pb2", "//modules/drivers/lidar/proto:velodyne_config_py_pb2", #"//modules/drivers/lidar/robosense/proto:lidars_filter_config_py_pb2", #"//modules/drivers/lidar/robosense/proto:sensor_suteng_conf_py_pb2", #"//modules/drivers/lidar/robosense/proto:sensor_suteng_py_pb2", "//modules/drivers/microphone/proto:microphone_config_py_pb2", "//modules/drivers/microphone/proto:audio_py_pb2", "//modules/drivers/radar/conti_radar/proto:conti_radar_conf_py_pb2", "//modules/drivers/radar/racobit_radar/proto:racobit_radar_conf_py_pb2", "//modules/drivers/radar/ultrasonic_radar/proto:ultrasonic_radar_conf_py_pb2", "//modules/drivers/smartereye/proto:config_py_pb2", "//modules/drivers/tools/image_decompress/proto:config_py_pb2", "//modules/drivers/video/proto:video_h265cfg_py_pb2" ], ) install_src_files( name = "install_src", deps = [ ":install_drivers_src", ":install_drivers_hdrs" ], ) install_src_files( name = "install_drivers_src", src_dir = ["."], dest = "drivers/src", filter = "*", ) install_src_files( name = "install_drivers_hdrs", src_dir = ["."], dest = "drivers/include", filter = "*.h", )
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/video/driver.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 "modules/drivers/video/driver.h" namespace apollo { namespace drivers { namespace video { using apollo::drivers::CompressedImage; using apollo::drivers::video::config::CameraH265Config; CameraDriver::CameraDriver(const CameraH265Config *h265_cfg) { config_ = *h265_cfg; } bool CameraDriver::Poll(std::shared_ptr<CompressedImage> h265) { return PollByFrame(h265); } bool CameraDriver::PollByFrame(std::shared_ptr<CompressedImage> h265Pb) { int ret = input_->GetFramePacket(h265Pb); if (ret < 0) { return false; } h265Pb->set_frame_id(config_.frame_id()); uint64_t camera_timestamp = h265Pb->mutable_header()->camera_timestamp(); uint64_t current_time = cyber::Time().Now().ToNanosecond(); AINFO << "Get frame from port: " << config_.udp_port() << ", size: " << h265Pb->data().size() << ", ts: camera/host " << camera_timestamp << "/" << current_time << ", diff: " << static_cast<double>(current_time - camera_timestamp) * 1e-6; return true; } void CameraDriver::Init() { input_.reset(new SocketInput()); input_->Init(config_.udp_port()); } } // namespace video } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/video/input.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. *****************************************************************************/ #pragma once #include <cstdint> namespace apollo { namespace drivers { namespace video { #ifdef __cplusplus extern "C" { #endif typedef struct RtpHeader { uint16_t csrc_count : 4; uint16_t extension : 1; uint16_t padding : 1; uint16_t version : 2; uint16_t payloadtype : 7; uint16_t marker : 1; uint16_t seq; uint32_t timestamp; uint32_t ssrc; } RtpHeader; #define HW_CAMERA_MAGIC0 0xBBAABBAA #define HW_CAMERA_MAGIC1 0xAABBAABB typedef struct FrameHeader { uint32_t magic0; /* 0xBBAABBAA */ uint32_t magic1; /* 0xAABBAABB */ // uint32_t ChanNo; uint8_t PhyNo; uint8_t frame_type; /* IDR: 1, other: 0 */ uint8_t error; /* error:1, other: 0 */ uint8_t resv; uint32_t frame_size; uint32_t frame_id; uint32_t ts_sec; uint32_t ts_usec; uint16_t height; /* 1920 */ uint16_t width; /* 1080 */ uint32_t format; /* H265 */ uint32_t resv0; uint32_t resv1; } FrameHeader; typedef struct HwPduPacket { RtpHeader rtp_header; FrameHeader header; } HwPduPacket; #ifdef __cplusplus } #endif } // namespace video } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/video/video_driver_component.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 "modules/drivers/video/video_driver_component.h" #include "cyber/common/file.h" namespace apollo { namespace drivers { namespace video { using cyber::common::EnsureDirectory; bool CompCameraH265Compressed::Init() { AINFO << "Initialize video driver component."; CameraH265Config video_config; if (!GetProtoConfig(&video_config)) { return false; } AINFO << "Velodyne config: " << video_config.DebugString(); camera_deivce_.reset(new CameraDriver(&video_config)); camera_deivce_->Init(); if (camera_deivce_->Record()) { // Use current directory to save record file if H265_SAVE_FOLDER environment // is not set. record_folder_ = cyber::common::GetEnv("H265_SAVE_FOLDER", "."); AINFO << "Record folder: " << record_folder_; struct stat st; if (stat(record_folder_.c_str(), &st) < 0) { bool ret = EnsureDirectory(record_folder_); AINFO_IF(ret) << "Record folder is created successfully."; } } pb_image_.reset(new CompressedImage); pb_image_->mutable_data()->reserve(1920 * 1080 * 4); writer_ = node_->CreateWriter<CompressedImage>( video_config.compress_conf().output_channel()); runing_ = true; video_thread_ = std::shared_ptr<std::thread>( new std::thread(std::bind(&CompCameraH265Compressed::VideoPoll, this))); video_thread_->detach(); return true; } void CompCameraH265Compressed::VideoPoll() { std::ofstream fout; if (camera_deivce_->Record()) { char name[256]; snprintf(name, sizeof(name), "%s/encode_%d.h265", record_folder_.c_str(), camera_deivce_->Port()); AINFO << "Output file: " << name; fout.open(name, std::ios::binary); if (!fout.good()) { AERROR << "Failed to open output file: " << name; } } int poll_failure_number = 0; while (!apollo::cyber::IsShutdown()) { if (!camera_deivce_->Poll(pb_image_)) { AERROR << "H265 poll failed on port: " << camera_deivce_->Port(); static constexpr int kTolerance = 256; if (++poll_failure_number > kTolerance) { AERROR << "H265 poll keep failing for " << kTolerance << " times, Exit"; break; } continue; } poll_failure_number = 0; pb_image_->mutable_header()->set_timestamp_sec( cyber::Time::Now().ToSecond()); AINFO << "Send compressed image."; writer_->Write(pb_image_); if (camera_deivce_->Record()) { fout.write(pb_image_->data().c_str(), pb_image_->data().size()); } } if (camera_deivce_->Record()) { fout.close(); } } } // namespace video } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/video/socket_input.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 <arpa/inet.h> #include <fcntl.h> #include <poll.h> #include <sys/file.h> #include <sys/socket.h> #include <unistd.h> #include <cerrno> #include <memory> #include "cyber/cyber.h" #include "modules/drivers/video/input.h" #include "modules/drivers/video/socket_input.h" namespace apollo { namespace drivers { namespace video { //////////////////////////////////////////////////////////////////////// // InputSocket class implementation //////////////////////////////////////////////////////////////////////// /** @brief constructor * * @param private_nh private node handle for driver * @param udpport UDP port number to connect */ SocketInput::SocketInput() : sockfd_(-1), port_(0) { pkg_num_ = 0; bytes_num_ = 0; frame_id_ = 0; } /** @brief destructor */ SocketInput::~SocketInput() { if (buf_) { delete[] buf_; } if (pdu_) { delete[] pdu_; } (void)close(sockfd_); } void SocketInput::Init(uint32_t port) { if (sockfd_ != -1) { (void)close(sockfd_); } sockfd_ = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd_ < 0) { AERROR << "Failed to create socket fd."; return; } // Connect to camera UDP port AINFO << "Opening UDP socket on port: " << uint16_t(port); port_ = port; sockaddr_in my_addr; memset(&my_addr, '\0', sizeof(my_addr)); my_addr.sin_family = AF_INET; my_addr.sin_port = htons(uint16_t(port)); my_addr.sin_addr.s_addr = INADDR_ANY; if (bind(sockfd_, reinterpret_cast<sockaddr *>(&my_addr), sizeof(sockaddr_in)) < 0) { AERROR << "Failed to bind socket on local address."; } if (fcntl(sockfd_, F_SETFL, O_NONBLOCK | FASYNC) < 0) { AERROR << "Failed to enable non-blocking I/O."; } const int rbuf = 4 * 1024 * 1024; if (setsockopt(sockfd_, SOL_SOCKET, SO_RCVBUF, &rbuf, sizeof(int)) < 0) { AERROR << "Failed to enable socket receive buffer."; } int enable = 1; if (setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) { AERROR << "Failed to enable socket reuseable address."; } buf_ = new uint8_t[H265_FRAME_PACKAGE_SIZE]; if (!buf_) { AERROR << "Failed to allocate H265 frame package buffer."; } pdu_ = new uint8_t[H265_PDU_SIZE]; if (!pdu_) { AERROR << "Failed to allocate H265 PDU buffer."; } // _metric_controller->Init(); AINFO << "Camera socket fd: " << sockfd_ << ", port: " << port_; } /** @brief Get one camera packet. */ int SocketInput::GetFramePacket(std::shared_ptr<CompressedImage> h265Pb) { uint8_t *frame_data = &buf_[0]; uint8_t *pdu_data = &pdu_[0]; int total = 0; int pkg_len = 0; size_t frame_len = 0; uint16_t pre_seq = 0; do { if (!InputAvailable(POLL_TIMEOUT)) { return SOCKET_TIMEOUT; } // Receive packets that should now be available from the socket using // a blocking read. ssize_t pdu_len = recvfrom(sockfd_, pdu_data, H265_PDU_SIZE, 0, NULL, NULL); if (pdu_len < 0) { if (errno != EWOULDBLOCK) { AERROR << "Failed to receive package from port: " << port_; return RECEIVE_FAIL; } } AINFO << "Received pdu length: " << pdu_len << " from port: " << port_; HwPduPacket *pdu_pkg = reinterpret_cast<HwPduPacket *>(&pdu_[0]); uint16_t local_seq = ntohs(pdu_pkg->rtp_header.seq); AINFO << "Package seq number: " << local_seq; if (local_seq - pre_seq != 1 && pre_seq > 1 && local_seq > 0) { AERROR << "Error! port: " << port_ << ", package sequence is wrong. curent/pre " << local_seq << "/" << pre_seq; } pre_seq = local_seq; if (ntohl(pdu_pkg->header.magic0) == HW_CAMERA_MAGIC0 && ntohl(pdu_pkg->header.magic1) == HW_CAMERA_MAGIC1) { // Receive camera frame head if (total) { AERROR << "Error! lost package for last frame, left bytes: " << total; } AINFO << "Received new frame from port: " << port_; uint32_t frame_id = ntohl(pdu_pkg->header.frame_id); if (frame_id - frame_id_ != 1 && frame_id_ > 1 && frame_id > 1) { AERROR << "Error! port: " << port_ << ", lose Frame. pre_frame_id/frame_id " << frame_id_ << "/" << frame_id; } frame_id_ = frame_id; cyber::Time image_time(ntohl(pdu_pkg->header.ts_sec), 1000 * ntohl(pdu_pkg->header.ts_usec)); // AINFO << "image_time second: " << ntohl(pdu_pkg->header.ts_sec) << // " usec: " << ntohl(pdu_pkg->header.ts_usec); uint64_t camera_timestamp = image_time.ToNanosecond(); h265Pb->mutable_header()->set_camera_timestamp(camera_timestamp); h265Pb->set_measurement_time(image_time.ToSecond()); h265Pb->set_format("h265"); h265Pb->set_frame_type(static_cast<int>(pdu_pkg->header.frame_type)); AINFO << "Port: " << port_ << ", received frame size: " << ntohl(pdu_pkg->header.frame_size) << ", frame type: " << static_cast<int>(pdu_pkg->header.frame_type) << ", PhyNo: " << static_cast<int>(pdu_pkg->header.PhyNo) << ", frame id: " << frame_id; frame_len = ntohl(pdu_pkg->header.frame_size); total = static_cast<int>(frame_len); frame_data = &buf_[0]; continue; } // Receive camera frame data if (total > 0) { pkg_len = static_cast<int>(pdu_len - sizeof(RtpHeader)); memcpy(frame_data, pdu_data + sizeof(RtpHeader), pkg_len); total -= pkg_len; frame_data += pkg_len; // AINFO << "receive pkg data " << pkg_len << "/" << total << "/" // << frame_len; } if (total <= 0) { total = 0; // AINFO << "receive frame data " << pkg_len << "/" << total << "/" // << frame_len; if (frame_len > 0) { h265Pb->set_data(buf_, frame_len); break; } AERROR << "Error! frame info is wrong. frame length: " << frame_len; } } while (true); return 0; } bool SocketInput::InputAvailable(int timeout) { (void)timeout; struct pollfd fds[1]; fds[0].fd = sockfd_; fds[0].events = POLLIN; // Unfortunately, the Linux kernel recvfrom() implementation // uses a non-interruptible sleep() when waiting for data, // which would cause this method to hang if the device is not // providing data. We poll() the device first to make sure // the recvfrom() will not block. // Note that, however, there is a known Linux kernel bug: // Under Linux, select() may report a socket file descriptor // as "ready for reading", while nevertheless a subsequent // read blocks. This could for example happen when data has // arrived but upon examination has wrong checksum and is // discarded. There may be other circumstances in which a // file descriptor is spuriously reported as ready. Thus it // may be safer to use O_NONBLOCK on sockets that should not // block. // poll() until input available do { int ret = poll(fds, 1, POLL_TIMEOUT); if (ret < 0) { if (errno != EINTR) { AERROR << "H265 camera port: " << port_ << "poll() error: " << strerror(errno); } return false; } // Timeout if (ret == 0) { return false; } if ((fds[0].revents & POLLERR) || (fds[0].revents & POLLHUP) || (fds[0].revents & POLLNVAL)) { AERROR << "Error! poll failed on H265 camera port: " << port_; return false; } } while (!(fds[0].revents & POLLIN)); return true; } } // namespace video } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/video/driver.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. *****************************************************************************/ #pragma once #include <memory> #include "cyber/cyber.h" #include "modules/common_msgs/sensor_msgs/sensor_image.pb.h" #include "modules/drivers/video/proto/video_h265cfg.pb.h" #include "modules/drivers/video/socket_input.h" namespace apollo { namespace drivers { namespace video { using apollo::drivers::CompressedImage; using apollo::drivers::video::config::CameraH265Config; class CameraDriver { public: explicit CameraDriver(const CameraH265Config *h265_cfg); ~CameraDriver() {} bool Poll(std::shared_ptr<CompressedImage> h265); void Init(); int Port() { return config_.udp_port(); } int Record() { return config_.record(); } protected: CameraH265Config config_; std::shared_ptr<SocketInput> input_; bool PollByFrame(std::shared_ptr<CompressedImage> h265); }; } // namespace video } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/video/BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library") load("//tools/install:install.bzl", "install") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) install( name = "install", data_dest = "drivers/addition_data/video", library_dest = "drivers/lib/video", data = [ ":runtime_files", ], targets = [ "libvideo_driver_component.so", ], ) filegroup( name = "runtime_files", srcs = glob([ "conf/*.txt", "dag/*.dag", "launch/*.launch", ]) ) cc_binary( name = "libvideo_driver_component.so", linkshared = True, linkstatic = True, deps = [":video_driver_component_lib"], ) cc_library( name = "video_driver_component_lib", srcs = ["video_driver_component.cc"], hdrs = ["video_driver_component.h"], copts = ['-DMODULE_NAME=\\"video\\"'], alwayslink = True, deps = [ "//cyber", "//modules/common/util:util_tool", "//modules/drivers/video:driver", "//modules/drivers/video:socket", ], ) cc_library( name = "driver", srcs = ["driver.cc"], hdrs = [ "driver.h", "socket_input.h", ], deps = [ "//cyber", "//modules/common_msgs/sensor_msgs:sensor_image_cc_proto", "//modules/drivers/video/proto:video_h265cfg_cc_proto", ], ) cc_library( name = "socket", srcs = ["socket_input.cc"], hdrs = [ "input.h", "socket_input.h", ], deps = [ "//cyber", "//modules/common_msgs/basic_msgs:error_code_cc_proto", "//modules/common_msgs/basic_msgs:header_cc_proto", "//modules/common/util", "//modules/common_msgs/sensor_msgs:sensor_image_cc_proto", ], ) cpplint()
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/video/socket_input.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. *****************************************************************************/ #pragma once #include <unistd.h> #include <cstdio> #include <map> #include <memory> #include <string> #include "cyber/cyber.h" #include "modules/common_msgs/sensor_msgs/sensor_image.pb.h" namespace apollo { namespace drivers { namespace video { static const int SOCKET_TIMEOUT = -2; static const int RECEIVE_FAIL = -3; static const int POLL_TIMEOUT = 1000; // one second (in msec) static const size_t H265_FRAME_PACKAGE_SIZE = 4 * 1024 * 1024; static const size_t H265_PDU_SIZE = 1500; /** @brief Live Velodyne input from socket. */ class SocketInput { public: SocketInput(); virtual ~SocketInput(); void Init(uint32_t port); int GetFramePacket(std::shared_ptr<CompressedImage> h265); private: int sockfd_; int port_; uint8_t *buf_ = nullptr; uint8_t *pdu_ = nullptr; int pkg_num_; int bytes_num_; uint32_t frame_id_; bool InputAvailable(int timeout); }; } // namespace video } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/video/video_driver_component.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. *****************************************************************************/ #pragma once #include <memory> #include <string> #include <thread> #include "cyber/base/concurrent_object_pool.h" #include "cyber/cyber.h" #include "modules/common_msgs/sensor_msgs/sensor_image.pb.h" #include "modules/drivers/video/driver.h" #include "modules/drivers/video/proto/video_h265cfg.pb.h" namespace apollo { namespace drivers { namespace video { using apollo::cyber::Component; using apollo::cyber::Writer; using apollo::cyber::base::CCObjectPool; using apollo::drivers::video::config::CameraH265Config; class CompCameraH265Compressed : public Component<> { public: ~CompCameraH265Compressed() { if (video_thread_->joinable()) { video_thread_->join(); } } bool Init(); private: void VideoPoll(); std::shared_ptr<apollo::cyber::Writer<CompressedImage>> writer_; std::shared_ptr<std::thread> video_thread_; volatile bool runing_; std::unique_ptr<CameraDriver> camera_deivce_; std::string record_folder_; std::shared_ptr<CompressedImage> pb_image_ = nullptr; }; CYBER_REGISTER_COMPONENT(CompCameraH265Compressed); } // namespace video } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/video/tools
apollo_public_repos/apollo/modules/drivers/video/tools/decode_video/video2jpg.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 "gflags/gflags.h" #include "cyber/common/log.h" #include "modules/drivers/video/tools/decode_video/frame_processor.h" using apollo::drivers::video::FrameProcessor; DECLARE_string(input_video); DECLARE_string(output_dir); DEFINE_string(input_video, "", "The input video file"); DEFINE_string(output_dir, "", "The directory to output decoded pictures."); int main(int argc, char** argv) { google::ParseCommandLineFlags(&argc, &argv, true); AINFO << "input video: " << FLAGS_input_video << ". output dir: " << FLAGS_output_dir; FrameProcessor processor(FLAGS_input_video, FLAGS_output_dir); if (!processor.ProcessStream()) { AERROR << "error: failed to decode file " << FLAGS_input_video; return -1; } return 0; }
0
apollo_public_repos/apollo/modules/drivers/video/tools
apollo_public_repos/apollo/modules/drivers/video/tools/decode_video/frame_processor.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 "modules/drivers/video/tools/decode_video/frame_processor.h" #include <fstream> #include <memory> #include <sstream> #include "absl/strings/str_cat.h" #include "cyber/common/log.h" #include "modules/drivers/video/tools/decode_video/h265_decoder.h" namespace apollo { namespace drivers { namespace video { FrameProcessor::FrameProcessor(const std::string& input_video_file, const std::string& output_jpg_dir) : output_jpg_dir_(output_jpg_dir) { std::ifstream video_file(input_video_file, std::ios::binary); std::istreambuf_iterator<char> buf_begin(video_file), buf_end; while (buf_begin != buf_end) { input_video_buffer_.emplace_back(*buf_begin++); } } bool FrameProcessor::ProcessStream() const { if (input_video_buffer_.empty()) { AERROR << "error: failed to read from input video file"; return false; } AVCodecParserContext* codec_parser = av_parser_init(AV_CODEC_ID_H265); if (codec_parser == nullptr) { AERROR << "error: failed to init AVCodecParserContext"; return false; } AVPacket apt; av_init_packet(&apt); const std::unique_ptr<H265Decoder> decoder(new H265Decoder()); if (!decoder->Init()) { AERROR << "error: failed to init decoder"; return false; } uint32_t local_size = static_cast<uint32_t>(input_video_buffer_.size()); uint8_t* local_data = const_cast<uint8_t*>(input_video_buffer_.data()); AINFO << "decoding: video size = " << local_size; int frame_num = 0; int warn_frame_num = 0; std::vector<uint8_t> jpeg_buffer; while (local_size > 0) { int frame_len = av_parser_parse2( codec_parser, decoder->GetCodecCtxH265(), &(apt.data), &(apt.size), local_data, local_size, AV_NOPTS_VALUE, AV_NOPTS_VALUE, AV_NOPTS_VALUE); if (apt.data == nullptr) { apt.data = local_data; apt.size = local_size; } AINFO << "frame " << frame_num << ": frame_len=" << frame_len << ". left_size=" << local_size; const auto decoding_result = decoder->Process(apt.data, apt.size, &jpeg_buffer); if (decoding_result != H265Decoder::DecodingResult::WARN) { // Write to output even if failed to convert, in order to // maintain the order of frames WriteOutputJpgFile(jpeg_buffer, GetOutputFile(frame_num)); ++frame_num; } else { // Retry later if returns warn, which indicates reading more from buffer ++warn_frame_num; } local_data += frame_len; local_size -= frame_len; } // Decode the left over frames from buffer exactly warning times for (int i = warn_frame_num; i > 0; --i) { // When retry to decode from buffer, we do not care if it succeeds or not decoder->Process(nullptr, 0, &jpeg_buffer); WriteOutputJpgFile(jpeg_buffer, GetOutputFile(frame_num)); AINFO << "frame " << frame_num << ": read from buffer"; ++frame_num; } AINFO << "total frames: " << frame_num; av_parser_close(codec_parser); return true; } std::string FrameProcessor::GetOutputFile(const int frame_num) const { static constexpr int kSuffixLen = 5; std::stringstream jpg_suffix; jpg_suffix.fill('0'); jpg_suffix.width(kSuffixLen); jpg_suffix << frame_num; return absl::StrCat(output_jpg_dir_, "/", jpg_suffix.str(), ".jpg"); } void FrameProcessor::WriteOutputJpgFile( const std::vector<uint8_t>& jpeg_buffer, const std::string& output_jpg_file) const { std::ofstream out(output_jpg_file, std::ios::binary); for (const uint8_t current : jpeg_buffer) { out << static_cast<char>(current); } } } // namespace video } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/video/tools
apollo_public_repos/apollo/modules/drivers/video/tools/decode_video/h265_decoder.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. *****************************************************************************/ #pragma once #include <vector> extern "C" { #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #include <libavutil/imgutils.h> #include <libswscale/swscale.h> } namespace apollo { namespace drivers { namespace video { /** * @class H265Decoder * @brief H265Decoder is a class to actually decode videos. */ class H265Decoder { public: enum class DecodingResult { SUCCESS, FATAL, WARN, }; public: H265Decoder() = default; // Init decoder by acquiring resources bool Init(); // Process frames according to input data, and output converted data DecodingResult Process(const uint8_t* indata, const int32_t insize, std::vector<uint8_t>* outdata) const; // Destructor, releasing the resources ~H265Decoder() { Release(); } // Getter of codec_ctx_h265_ AVCodecContext* GetCodecCtxH265() const { return codec_ctx_h265_; } private: void Release(); AVCodecContext* codec_ctx_h265_ = nullptr; AVCodecContext* codec_ctx_jpeg_ = nullptr; AVFrame* yuv_frame_ = nullptr; }; } // namespace video } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/video/tools
apollo_public_repos/apollo/modules/drivers/video/tools/decode_video/frame_processor.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. *****************************************************************************/ #pragma once #include <string> #include <vector> namespace apollo { namespace drivers { namespace video { /** * @class FrameProcessor * @brief FrameProcessor is a class to process video streams. */ class FrameProcessor { public: // Constructor FrameProcessor(const std::string& input_video_file, const std::string& output_jpg_dir); // Process frames according to input data, and output converted data bool ProcessStream() const; // Destructor ~FrameProcessor() = default; private: void WriteOutputJpgFile(const std::vector<uint8_t>& jpeg_buffer, const std::string& output_jpg_file) const; std::string GetOutputFile(const int frame_num) const; std::vector<uint8_t> input_video_buffer_; const std::string output_jpg_dir_; }; } // namespace video } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/video/tools
apollo_public_repos/apollo/modules/drivers/video/tools/decode_video/h265_decoder.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 <algorithm> #include "cyber/common/log.h" #include "modules/drivers/video/tools/decode_video/h265_decoder.h" namespace apollo { namespace drivers { namespace video { // Using to-be-deprecated avcodec_decode_video2 for now until its replacement // gets stable #pragma GCC diagnostic ignored "-Wdeprecated-declarations" bool H265Decoder::Init() { avcodec_register_all(); AVCodec* codec_h265 = avcodec_find_decoder(AV_CODEC_ID_H265); if (codec_h265 == nullptr) { AERROR << "error: codec not found"; return false; } codec_ctx_h265_ = avcodec_alloc_context3(codec_h265); if (codec_ctx_h265_ == nullptr) { AERROR << "error: codec context alloc fail"; return false; } if (avcodec_open2(codec_ctx_h265_, codec_h265, nullptr) < 0) { AERROR << "error: could not open codec"; return false; } yuv_frame_ = av_frame_alloc(); if (yuv_frame_ == nullptr) { AERROR << "error: could not alloc yuv frame"; return false; } AVCodec* codec_jpeg = avcodec_find_encoder(AV_CODEC_ID_MJPEG); if (codec_jpeg == nullptr) { AERROR << "error: jpeg Codec not found"; return false; } codec_ctx_jpeg_ = avcodec_alloc_context3(codec_jpeg); if (codec_ctx_jpeg_ == nullptr) { AERROR << "error: jpeg ctx allco fail"; return false; } // Put sample parameters and open it codec_ctx_jpeg_->bit_rate = 400000; codec_ctx_jpeg_->codec_type = AVMEDIA_TYPE_VIDEO; codec_ctx_jpeg_->codec_id = AV_CODEC_ID_MJPEG; codec_ctx_jpeg_->width = 1920; codec_ctx_jpeg_->height = 1080; codec_ctx_jpeg_->time_base = (AVRational){1, 15}; codec_ctx_jpeg_->pix_fmt = AV_PIX_FMT_YUVJ422P; if (avcodec_open2(codec_ctx_jpeg_, codec_jpeg, nullptr) < 0) { AERROR << "error: could not open jpeg context"; return false; } return true; } void H265Decoder::Release() { if (codec_ctx_h265_ != nullptr) { avcodec_free_context(&codec_ctx_h265_); codec_ctx_h265_ = nullptr; } if (yuv_frame_ != nullptr) { av_frame_free(&yuv_frame_); yuv_frame_ = nullptr; } if (codec_ctx_jpeg_ != nullptr) { avcodec_free_context(&codec_ctx_jpeg_); codec_ctx_jpeg_ = nullptr; } } H265Decoder::DecodingResult H265Decoder::Process( const uint8_t* indata, const int32_t insize, std::vector<uint8_t>* outdata) const { AVPacket apt; outdata->clear(); av_init_packet(&apt); int got_picture = 0; apt.data = const_cast<uint8_t*>(indata); apt.size = insize; if (apt.size == 0) { apt.data = nullptr; } int ret = avcodec_decode_video2(codec_ctx_h265_, yuv_frame_, &got_picture, &apt); if (ret < 0) { AERROR << "error: decode failed: input_framesize = " << apt.size << ". error code = " << ret; return H265Decoder::DecodingResult::FATAL; } if (!got_picture) { // Not an error, but just did not read pictures out AWARN << "warn: failed to get yuv picture"; return H265Decoder::DecodingResult::WARN; } av_packet_unref(&apt); got_picture = 0; ret = avcodec_encode_video2(codec_ctx_jpeg_, &apt, yuv_frame_, &got_picture); if (ret < 0) { AERROR << "error: jpeg encode failed, error code = " << ret; return H265Decoder::DecodingResult::FATAL; } if (!got_picture) { AERROR << "error: failed to get jpeg picture from yuyv"; return H265Decoder::DecodingResult::FATAL; } outdata->resize(apt.size); std::copy(apt.data, apt.data + apt.size, outdata->begin()); return H265Decoder::DecodingResult::SUCCESS; } } // namespace video } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/video/tools
apollo_public_repos/apollo/modules/drivers/video/tools/decode_video/BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library") load("//tools:cpplint.bzl", "cpplint") load("//tools/install:install.bzl", "install") package(default_visibility = ["//visibility:public"]) install( name = "install", runtime_dest = "drivers/bin", targets = [ ":video2jpg", ], ) cc_binary( name = "video2jpg", srcs = ["video2jpg.cc"], deps = [ ":frame_processor", "@com_github_gflags_gflags//:gflags", "@ffmpeg//:avutil", ], ) cc_library( name = "frame_processor", srcs = ["frame_processor.cc"], hdrs = ["frame_processor.h"], deps = [ ":h265_decoder", "//modules/common/util", "@com_google_absl//:absl", ], ) cc_library( name = "h265_decoder", srcs = ["h265_decoder.cc"], hdrs = ["h265_decoder.h"], deps = [ "//cyber", "@ffmpeg//:avcodec", ], ) cpplint()
0
apollo_public_repos/apollo/modules/drivers/video
apollo_public_repos/apollo/modules/drivers/video/proto/video_h265cfg.proto
syntax = "proto2"; package apollo.drivers.video.config; message CameraH265Config { required uint32 udp_port = 1; // required string camera_dev = 1; required string frame_id = 2; // v4l pixel format required string pixel_format = 3 [default = "yuyv"]; // mmap, userptr, read // required IOMethod io_method = 4; required uint32 record = 4; required uint32 width = 5; required uint32 height = 6; required uint32 frame_rate = 7; required bool monochrome = 8 [default = false]; required int32 brightness = 9 [default = -1]; required int32 contrast = 10 [default = -1]; required int32 saturation = 11 [default = -1]; required int32 sharpness = 12 [default = -1]; required int32 gain = 13 [default = -1]; required bool auto_focus = 14 [default = false]; required int32 focus = 15 [default = -1]; required bool auto_exposure = 16 [default = true]; required int32 exposure = 17 [default = 100]; required bool auto_white_balance = 18 [default = true]; required int32 white_balance = 19 [default = 4000]; required uint32 bytes_per_pixel = 20 [default = 3]; required string trigger_param = 21 [default = "f2ff"]; required uint32 metric_error_code = 22 [default = 11]; required int32 fpga_dev_number = 23 [default = -1]; required int32 camera_seq_number = 24 [default = -1]; message CompressConfig { optional string output_channel = 1; optional uint32 image_pool_size = 2 [default = 20]; } optional CompressConfig compress_conf = 25; }
0
apollo_public_repos/apollo/modules/drivers/video
apollo_public_repos/apollo/modules/drivers/video/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") package(default_visibility = ["//visibility:public"]) cc_proto_library( name = "video_h265cfg_cc_proto", deps = [ ":video_h265cfg_proto", ], ) proto_library( name = "video_h265cfg_proto", srcs = ["video_h265cfg.proto"], ) py_proto_library( name = "video_h265cfg_py_pb2", deps = [ ":video_h265cfg_proto", ], )
0
apollo_public_repos/apollo/modules/drivers/video
apollo_public_repos/apollo/modules/drivers/video/launch/video.launch
<cyber> <module> <name>video</name> <dag_conf>/apollo/modules/drivers/video/dag/video.dag</dag_conf> <process_name>h265_video</process_name> </module> </cyber>
0
apollo_public_repos/apollo/modules/drivers/video
apollo_public_repos/apollo/modules/drivers/video/dag/video.dag
# Define all coms in DAG streaming. module_config { module_library : "/apollo/bazel-bin/modules/drivers/video/libvideo_driver_component.so" components { class_name : "CompCameraH265Compressed" config { name : "camera_front_6mm_compress" config_file_path : "/apollo/modules/drivers/video/conf/video_front_6mm.pb.txt" } } components { class_name : "CompCameraH265Compressed" config { name : "camera_front_12mm_compress" config_file_path : "/apollo/modules/drivers/video/conf/video_front_12mm.pb.txt" } } components { class_name : "CompCameraH265Compressed" config { name : "camera_left_fisheye_compress" config_file_path : "/apollo/modules/drivers/video/conf/video_left_fisheye.pb.txt" } } components { class_name : "CompCameraH265Compressed" config { name : "camera_right_fisheye_compress" config_file_path : "/apollo/modules/drivers/video/conf/video_right_fisheye.pb.txt" } } components { class_name : "CompCameraH265Compressed" config { name : "camera_rear_6mm_compress" config_file_path : "/apollo/modules/drivers/video/conf/video_rear_6mm.pb.txt" } } }
0
apollo_public_repos/apollo/modules/drivers/video
apollo_public_repos/apollo/modules/drivers/video/conf/video_left_fisheye.pb.txt
udp_port: 2005 frame_id: "video_left_fisheye" pixel_format: "yuyv" trigger_param: "f2ff" metric_error_code: 32 record:0 width: 1920 height: 1080 frame_rate: 5 monochrome: false brightness: -1 contrast: -1 saturation: -1 sharpness: -1 gain: -1 auto_focus: false focus: -1 auto_exposure: true exposure: 100 auto_white_balance: true white_balance: 4000 bytes_per_pixel: 3 fpga_dev_number: 0 camera_seq_number: 6 compress_conf { output_channel: "/apollo/sensor/camera/left_fisheye/image/compressed" image_pool_size: 100 }
0
apollo_public_repos/apollo/modules/drivers/video
apollo_public_repos/apollo/modules/drivers/video/conf/video_right_rear.pb.txt
udp_port: 2007 frame_id: "video_right_rear" pixel_format: "yuyv" trigger_param: "f2ff" metric_error_code: 31 record:0 width: 1920 height: 1080 frame_rate: 5 monochrome: false brightness: -1 contrast: -1 saturation: -1 sharpness: -1 gain: -1 auto_focus: false focus: -1 auto_exposure: true exposure: 100 auto_white_balance: true white_balance: 4000 bytes_per_pixel: 3 fpga_dev_number: 0 camera_seq_number: 5 compress_conf { output_channel: "/apollo/sensor/camera/right_rear/image/compressed" image_pool_size: 100 }
0
apollo_public_repos/apollo/modules/drivers/video
apollo_public_repos/apollo/modules/drivers/video/conf/video_front_fisheye.pb.txt
udp_port: 2002 frame_id: "video_front_fisheye" pixel_format: "yuyv" trigger_param: "f2ff" metric_error_code: 14 record:0 width: 1920 height: 1080 frame_rate: 15 monochrome: false brightness: -1 contrast: -1 saturation: -1 sharpness: -1 gain: -1 auto_focus: false focus: -1 auto_exposure: true exposure: 100 auto_white_balance: true white_balance: 4000 bytes_per_pixel: 3 fpga_dev_number: 0 camera_seq_number: 1 compress_conf { output_channel: "/apollo/sensor/camera/front_fisheye/image/compressed" image_pool_size: 100 }
0
apollo_public_repos/apollo/modules/drivers/video
apollo_public_repos/apollo/modules/drivers/video/conf/video_left_front.pb.txt
udp_port: 2003 frame_id: "video_left_front" pixel_format: "yuyv" trigger_param: "f2ff" metric_error_code: 11 record:0 width: 1920 height: 1080 frame_rate: 15 monochrome: false brightness: -1 contrast: -1 saturation: -1 sharpness: -1 gain: -1 auto_focus: false focus: -1 auto_exposure: true exposure: 100 auto_white_balance: true white_balance: 4000 bytes_per_pixel: 3 fpga_dev_number: 0 camera_seq_number: 0 compress_conf { output_channel: "/apollo/sensor/camera/left_front/image/compressed" image_pool_size: 100 }
0
apollo_public_repos/apollo/modules/drivers/video
apollo_public_repos/apollo/modules/drivers/video/conf/video_left_rear.pb.txt
udp_port: 2004 frame_id: "video_left_rear" pixel_format: "yuyv" trigger_param: "f2ff" metric_error_code: 34 record:0 width: 1920 height: 1080 frame_rate: 5 monochrome: false brightness: -1 contrast: -1 saturation: -1 sharpness: -1 gain: -1 auto_focus: false focus: -1 auto_exposure: true exposure: 100 auto_white_balance: true white_balance: 4000 bytes_per_pixel: 3 fpga_dev_number: 0 camera_seq_number: 8 compress_conf { output_channel: "/apollo/sensor/camera/left_rear/image/compressed" image_pool_size: 100 }
0
apollo_public_repos/apollo/modules/drivers/video
apollo_public_repos/apollo/modules/drivers/video/conf/video_right_front.pb.txt
udp_port: 2006 frame_id: "video_right_front" pixel_format: "yuyv" trigger_param: "f2ff" metric_error_code: 30 record:0 width: 1920 height: 1080 frame_rate: 15 monochrome: false brightness: -1 contrast: -1 saturation: -1 sharpness: -1 gain: -1 auto_focus: false focus: -1 auto_exposure: true exposure: 100 auto_white_balance: true white_balance: 4000 bytes_per_pixel: 3 fpga_dev_number: 0 camera_seq_number: 4 compress_conf { output_channel: "/apollo/sensor/camera/right_front/image/compressed" image_pool_size: 100 }
0
apollo_public_repos/apollo/modules/drivers/video
apollo_public_repos/apollo/modules/drivers/video/conf/video_front_6mm.pb.txt
udp_port: 2000 frame_id: "video_front_6mm" pixel_format: "yuyv" trigger_param: "f2ff" metric_error_code: 18 record:0 width: 1920 height: 1080 frame_rate: 15 monochrome: false brightness: -1 contrast: -1 saturation: -1 sharpness: -1 gain: -1 auto_focus: false focus: -1 auto_exposure: true exposure: 100 auto_white_balance: true white_balance: 4000 bytes_per_pixel: 3 fpga_dev_number: 0 camera_seq_number: 3 compress_conf { output_channel: "/apollo/sensor/camera/front_6mm/image/compressed" image_pool_size: 100 }
0
apollo_public_repos/apollo/modules/drivers/video
apollo_public_repos/apollo/modules/drivers/video/conf/video_front_12mm.pb.txt
udp_port: 2001 frame_id: "video_front_12mm" pixel_format: "yuyv" trigger_param: "f2ff" metric_error_code: 17 record:0 width: 1920 height: 1080 frame_rate: 15 monochrome: false brightness: -1 contrast: -1 saturation: -1 sharpness: -1 gain: -1 auto_focus: false focus: -1 auto_exposure: true exposure: 100 auto_white_balance: true white_balance: 4000 bytes_per_pixel: 3 fpga_dev_number: 0 camera_seq_number: 2 compress_conf { output_channel: "/apollo/sensor/camera/front_12mm/image/compressed" image_pool_size: 100 }
0
apollo_public_repos/apollo/modules/drivers/video
apollo_public_repos/apollo/modules/drivers/video/conf/video_right_fisheye.pb.txt
udp_port: 2008 frame_id: "video_right_fisheye" pixel_format: "yuyv" trigger_param: "f2ff" metric_error_code: 33 record:0 width: 1920 height: 1080 frame_rate: 5 monochrome: false brightness: -1 contrast: -1 saturation: -1 sharpness: -1 gain: -1 auto_focus: false focus: -1 auto_exposure: true exposure: 100 auto_white_balance: true white_balance: 4000 bytes_per_pixel: 3 fpga_dev_number: 0 camera_seq_number: 7 compress_conf { output_channel: "/apollo/sensor/camera/right_fisheye/image/compressed" image_pool_size: 100 }
0
apollo_public_repos/apollo/modules/drivers/video
apollo_public_repos/apollo/modules/drivers/video/conf/video_rear_6mm.pb.txt
udp_port: 2009 frame_id: "video_rear_6mm" pixel_format: "yuyv" trigger_param: "f2ff" metric_error_code: 18 record:0 width: 1920 height: 1080 frame_rate: 15 monochrome: false brightness: -1 contrast: -1 saturation: -1 sharpness: -1 gain: -1 auto_focus: false focus: -1 auto_exposure: true exposure: 100 auto_white_balance: true white_balance: 4000 bytes_per_pixel: 3 fpga_dev_number: 0 camera_seq_number: 3 compress_conf { output_channel: "/apollo/sensor/camera/rear_6mm/image/compressed" image_pool_size: 100 }
0
apollo_public_repos/apollo/modules/drivers/tools
apollo_public_repos/apollo/modules/drivers/tools/image_decompress/image_decompress_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 "modules/drivers/tools/image_decompress/image_decompress.h" #include "cyber/init.h" #include "gtest/gtest.h" namespace apollo { namespace image_decompress { TEST(ImageDecompressComponentTest, Init) { cyber::Init("image_decompress_component_test"); ImageDecompressComponent component; } } // namespace image_decompress } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/tools
apollo_public_repos/apollo/modules/drivers/tools/image_decompress/image_decompress.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. *****************************************************************************/ #pragma once #include <memory> #include "cyber/component/component.h" #include "modules/common_msgs/sensor_msgs/sensor_image.pb.h" #include "modules/drivers/tools/image_decompress/proto/config.pb.h" namespace apollo { namespace image_decompress { class ImageDecompressComponent final : public cyber::Component<apollo::drivers::CompressedImage> { public: bool Init() override; bool Proc( const std::shared_ptr<apollo::drivers::CompressedImage>& image) override; private: std::shared_ptr<cyber::Writer<apollo::drivers::Image>> writer_; Config config_; }; CYBER_REGISTER_COMPONENT(ImageDecompressComponent) } // namespace image_decompress } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/tools
apollo_public_repos/apollo/modules/drivers/tools/image_decompress/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 = "drivers/lib/tools/image_decompress", data_dest = "drivers/addition_data/tools/image_decompress", data = [ ":runtime_data", ], targets = [ ":libimage_decompress.so", ], ) filegroup( name = "runtime_data", srcs = glob([ "conf/*.txt", "dag/*.dag", "launch/*.launch", ]), ) cc_library( name = "image_decompress_lib", srcs = ["image_decompress.cc"], hdrs = ["image_decompress.h"], copts = ['-DMODULE_NAME=\\"image_decompress\\"'], alwayslink = True, deps = [ "//cyber", "//modules/common_msgs/basic_msgs:error_code_cc_proto", "//modules/common_msgs/basic_msgs:header_cc_proto", "//modules/common_msgs/sensor_msgs:sensor_image_cc_proto", "//modules/drivers/tools/image_decompress/proto:config_cc_proto", "@opencv//:imgcodecs", ], ) cc_test( name = "image_decompress_test", size = "small", srcs = ["image_decompress_test.cc"], deps = [ ":image_decompress_lib", "@com_google_googletest//:gtest_main", ], ) cc_binary( name = "libimage_decompress.so", linkshared = True, linkstatic = True, deps = [":image_decompress_lib"], ) cpplint()
0
apollo_public_repos/apollo/modules/drivers/tools
apollo_public_repos/apollo/modules/drivers/tools/image_decompress/image_decompress.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 "modules/drivers/tools/image_decompress/image_decompress.h" #include <vector> #include "opencv2/opencv.hpp" namespace apollo { namespace image_decompress { using apollo::drivers::Image; bool ImageDecompressComponent::Init() { if (!GetProtoConfig(&config_)) { AERROR << "Parse config file failed: " << ConfigFilePath(); return false; } AINFO << "Decompress config: \n" << config_.DebugString(); writer_ = node_->CreateWriter<Image>(config_.channel_name()); return true; } bool ImageDecompressComponent::Proc( const std::shared_ptr<apollo::drivers::CompressedImage>& compressed_image) { auto image = std::make_shared<Image>(); image->mutable_header()->CopyFrom(compressed_image->header()); if (compressed_image->has_measurement_time()) { image->set_measurement_time(compressed_image->measurement_time()); } else { image->set_measurement_time(compressed_image->header().timestamp_sec()); } std::vector<uint8_t> compressed_raw_data(compressed_image->data().begin(), compressed_image->data().end()); cv::Mat mat_image = cv::imdecode(compressed_raw_data, cv::IMREAD_COLOR); cv::cvtColor(mat_image, mat_image, cv::COLOR_BGR2RGB); image->set_width(mat_image.cols); image->set_height(mat_image.rows); // Now olny rgb image->set_encoding("rgb8"); image->set_step(3 * image->width()); auto size = mat_image.step * mat_image.rows; image->set_data(&(mat_image.data[0]), size); writer_->Write(image); return true; } } // namespace image_decompress } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/tools/image_decompress
apollo_public_repos/apollo/modules/drivers/tools/image_decompress/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") package(default_visibility = ["//visibility:public"]) cc_proto_library( name = "config_cc_proto", deps = [ ":config_proto", ], ) proto_library( name = "config_proto", srcs = ["config.proto"], ) py_proto_library( name = "config_py_pb2", deps = [ ":config_proto", ], )
0
apollo_public_repos/apollo/modules/drivers/tools/image_decompress
apollo_public_repos/apollo/modules/drivers/tools/image_decompress/proto/config.proto
syntax = "proto2"; package apollo.image_decompress; message Config { optional string channel_name = 1; }
0
apollo_public_repos/apollo/modules/drivers/tools/image_decompress
apollo_public_repos/apollo/modules/drivers/tools/image_decompress/launch/image_decompress.launch
<cyber> <module> <name>image_decompress</name> <dag_conf>/apollo/modules/drivers/tools/image_decompress/dag/image_decompress.dag</dag_conf> <process_name></process_name> </module> </cyber>
0
apollo_public_repos/apollo/modules/drivers/tools/image_decompress
apollo_public_repos/apollo/modules/drivers/tools/image_decompress/dag/image_decompress.dag
# Define all coms in DAG streaming. module_config { module_library : "/apollo/bazel-bin/modules/drivers/tools/image_decompress/libimage_decompress.so" components { class_name : "ImageDecompressComponent" config { name : "camera_front_6mm_decompress" config_file_path : "/apollo/modules/drivers/tools/image_decompress/conf/camera_front_6mm.pb.txt" readers { channel: "/apollo/sensor/camera/front_6mm/image/compressed" pending_queue_size: 10 } } } components { class_name : "ImageDecompressComponent" config { name : "camera_front_12mm_decompress" config_file_path : "/apollo/modules/drivers/tools/image_decompress/conf/camera_front_12mm.pb.txt" readers { channel: "/apollo/sensor/camera/front_12mm/image/compressed" pending_queue_size: 10 } } } # components { # class_name : "ImageDecompressComponent" # config { # name : "camera_front_fisheye_decompress" # config_file_path : "/apollo/modules/drivers/tools/image_decompress/conf/camera_front_fisheye.pb.txt" # readers { # channel: "/apollo/sensor/camera/front_fisheye/image/compressed" # pending_queue_size: 10 # } # } # } # components { # class_name : "ImageDecompressComponent" # config { # name : "camera_left_front_decompress" # config_file_path : "/apollo/modules/drivers/tools/image_decompress/conf/camera_left_front.pb.txt" # readers { # channel: "/apollo/sensor/camera/left_front/image/compressed" # pending_queue_size: 10 # } # } # } # components { # class_name : "ImageDecompressComponent" # config { # name : "camera_left_rear_decompress" # config_file_path : "/apollo/modules/drivers/tools/image_decompress/conf/camera_left_rear.pb.txt" # readers { # channel: "/apollo/sensor/camera/left_rear/image/compressed" # pending_queue_size: 10 # } # } # } components { class_name : "ImageDecompressComponent" config { name : "camera_left_fisheye_decompress" config_file_path : "/apollo/modules/drivers/tools/image_decompress/conf/camera_left_fisheye.pb.txt" readers { channel: "/apollo/sensor/camera/left_fisheye/image/compressed" pending_queue_size: 10 } } } # components { # class_name : "ImageDecompressComponent" # config { # name : "camera_right_front_decompress" # config_file_path : "/apollo/modules/drivers/tools/image_decompress/conf/camera_right_front.pb.txt" # readers { # channel: "/apollo/sensor/camera/right_front/image/compressed" # pending_queue_size: 10 # } # } # } # components { # class_name : "ImageDecompressComponent" # config { # name : "camera_right_rear_decompress" # config_file_path : "/apollo/modules/drivers/tools/image_decompress/conf/camera_right_rear.pb.txt" # readers { # channel: "/apollo/sensor/camera/right_rear/image/compressed" # pending_queue_size: 10 # } # } # } components { class_name : "ImageDecompressComponent" config { name : "camera_right_fisheye_decompress" config_file_path : "/apollo/modules/drivers/tools/image_decompress/conf/camera_right_fisheye.pb.txt" readers { channel: "/apollo/sensor/camera/right_fisheye/image/compressed" pending_queue_size: 10 } } } components { class_name : "ImageDecompressComponent" config { name : "camera_rear_6mm_decompress" config_file_path : "/apollo/modules/drivers/tools/image_decompress/conf/camera_rear_6mm.pb.txt" readers { channel: "/apollo/sensor/camera/rear_6mm/image/compressed" pending_queue_size: 10 } } } }
0
apollo_public_repos/apollo/modules/drivers/tools/image_decompress
apollo_public_repos/apollo/modules/drivers/tools/image_decompress/conf/camera_short_conf.pb.txt
channel_name: "/apollo/sensor/camera/traffic/image_short"
0
apollo_public_repos/apollo/modules/drivers/tools/image_decompress
apollo_public_repos/apollo/modules/drivers/tools/image_decompress/conf/camera_front_conf.pb.txt
channel_name: "/apollo/sensor/camera/obstacle/front_6mm"
0
apollo_public_repos/apollo/modules/drivers/tools/image_decompress
apollo_public_repos/apollo/modules/drivers/tools/image_decompress/conf/camera_right_rear.pb.txt
channel_name: "/apollo/sensor/camera/right_rear/image"
0
apollo_public_repos/apollo/modules/drivers/tools/image_decompress
apollo_public_repos/apollo/modules/drivers/tools/image_decompress/conf/camera_long_conf.pb.txt
channel_name: "/apollo/sensor/camera/traffic/image_long"
0
apollo_public_repos/apollo/modules/drivers/tools/image_decompress
apollo_public_repos/apollo/modules/drivers/tools/image_decompress/conf/camera_right_fisheye.pb.txt
channel_name: "/apollo/sensor/camera/right_fisheye/image"
0
apollo_public_repos/apollo/modules/drivers/tools/image_decompress
apollo_public_repos/apollo/modules/drivers/tools/image_decompress/conf/camera_rear_6mm.pb.txt
channel_name: "/apollo/sensor/camera/rear_6mm/image"
0
apollo_public_repos/apollo/modules/drivers/tools/image_decompress
apollo_public_repos/apollo/modules/drivers/tools/image_decompress/conf/camera_left_front.pb.txt
channel_name: "/apollo/sensor/camera/left_front/image"
0
apollo_public_repos/apollo/modules/drivers/tools/image_decompress
apollo_public_repos/apollo/modules/drivers/tools/image_decompress/conf/camera_left_fisheye.pb.txt
channel_name: "/apollo/sensor/camera/left_fisheye/image"
0
apollo_public_repos/apollo/modules/drivers/tools/image_decompress
apollo_public_repos/apollo/modules/drivers/tools/image_decompress/conf/camera_right_front.pb.txt
channel_name: "/apollo/sensor/camera/right_front/image"
0
apollo_public_repos/apollo/modules/drivers/tools/image_decompress
apollo_public_repos/apollo/modules/drivers/tools/image_decompress/conf/camera_front_6mm.pb.txt
channel_name: "/apollo/sensor/camera/front_6mm/image"
0
apollo_public_repos/apollo/modules/drivers/tools/image_decompress
apollo_public_repos/apollo/modules/drivers/tools/image_decompress/conf/camera_front_fisheye.pb.txt
channel_name: "/apollo/sensor/camera/front_fisheye/image"
0
apollo_public_repos/apollo/modules/drivers/tools/image_decompress
apollo_public_repos/apollo/modules/drivers/tools/image_decompress/conf/camera_left_rear.pb.txt
channel_name: "/apollo/sensor/camera/left_rear/image"
0
apollo_public_repos/apollo/modules/drivers/tools/image_decompress
apollo_public_repos/apollo/modules/drivers/tools/image_decompress/conf/camera_front_12mm.pb.txt
channel_name: "/apollo/sensor/camera/front_12mm/image"
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/microphone/microphone_component.cc
/****************************************************************************** * Copyright 2020 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 "modules/drivers/microphone/microphone_component.h" namespace apollo { namespace drivers { namespace microphone { bool MicrophoneComponent::Init() { microphone_config_ptr_ = std::make_shared<MicrophoneConfig>(); if (!apollo::cyber::common::GetProtoFromFile(config_file_path_, microphone_config_ptr_.get())) { return false; } AINFO << "Microphone config: " << microphone_config_ptr_->DebugString(); // new microphone device microphone_device_ptr_.reset(new Respeaker()); microphone_device_ptr_->init(microphone_config_ptr_); // dump config, calculate size and reserve buffer for audio n_channels_ = microphone_config_ptr_->channel_type_size(); sample_width_ = microphone_config_ptr_->sample_width(); // chunk_: number of frames per chunk; chunk_size_: number of bytes per chunk chunk_ = microphone_config_ptr_->chunk(); n_chunk_ = static_cast<int>( std::ceil(microphone_config_ptr_->sample_rate() * microphone_config_ptr_->record_seconds() / chunk_)); chunk_size_ = chunk_ * n_channels_ * sample_width_; buffer_ = new char[chunk_size_]; if (buffer_ == nullptr) { AERROR << "System new memory error, size:" << chunk_size_; return false; } // assemble AudioData -- fill microphone_config, allocate memory for // channel_data audio_data_ptr_.reset(new AudioData()); std::string config; microphone_config_ptr_->SerializeToString(&config); audio_data_ptr_->mutable_microphone_config()->ParseFromString(config); audio_data_ptr_->mutable_header()->set_frame_id( microphone_config_ptr_->frame_id()); ChannelData *channel_data = nullptr; int channel_size = n_chunk_ * chunk_ * sample_width_; for (int i = 0; i < n_channels_; ++i) { channel_data = audio_data_ptr_->add_channel_data(); channel_data->set_channel_type(microphone_config_ptr_->channel_type(i)); channel_data->mutable_data()->resize(channel_size); channel_data_ptrs_.push_back(channel_data->mutable_data()); } writer_ptr_ = node_->CreateWriter<AudioData>(microphone_config_ptr_->channel_name()); async_result_ = cyber::Async(&MicrophoneComponent::run, this); return true; } void MicrophoneComponent::fill_channel_data(int chunk_i) { // next index of channel data to be filled int pos = chunk_i * chunk_ * sample_width_; for (int buff_i = 0; buff_i < chunk_size_; pos += sample_width_) { for (int channel_i = 0; channel_i < n_channels_; ++channel_i) { for (int di = 0; di < sample_width_; ++di) { (*channel_data_ptrs_[channel_i])[pos + di] = buffer_[buff_i++]; } } } } void MicrophoneComponent::run() { int chunk_i; while (!cyber::IsShutdown()) { try { for (chunk_i = 0; chunk_i < n_chunk_; ++chunk_i) { microphone_device_ptr_->read_stream(chunk_, buffer_); fill_channel_data(chunk_i); } } catch (const std::exception &e) { return; } FillHeader(node_->Name(), audio_data_ptr_.get()); writer_ptr_->Write(audio_data_ptr_); } } MicrophoneComponent::~MicrophoneComponent() { free(buffer_); if (running_.load()) { running_.exchange(false); async_result_.wait(); } } } // namespace microphone } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/microphone/respeaker.cc
/****************************************************************************** * Copyright 2020 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 "modules/drivers/microphone/respeaker.h" namespace apollo { namespace drivers { namespace microphone { PaError err; // Helper functions void report_error(PaError err, const std::string &func_name) { AERROR << "an error occured while calling " << func_name; AERROR << "error number: " << err; AERROR << "error message: " << Pa_GetErrorText(err); } // Stream Stream::~Stream() { Pa_CloseStream(pastream_ptr_); free(input_parameters_ptr_); } void Stream::init_stream(int rate, int channels, int chunk, int input_device_index, PaSampleFormat format) { // Init parameters of input device input_parameters_ptr_ = new PaStreamParameters; input_parameters_ptr_->device = input_device_index; input_parameters_ptr_->channelCount = channels; input_parameters_ptr_->sampleFormat = format; input_parameters_ptr_->suggestedLatency = Pa_GetDeviceInfo(input_parameters_ptr_->device)->defaultLowInputLatency; input_parameters_ptr_->hostApiSpecificStreamInfo = nullptr; err = Pa_OpenStream( &pastream_ptr_, input_parameters_ptr_, nullptr, rate, chunk, paClipOff, // we only use input so don't bother clipping them * nullptr, nullptr); if (err != paNoError) { report_error(err, "Pa_OpenStream"); } err = Pa_StartStream(pastream_ptr_); if (err != paNoError) { report_error(err, "Pa_StartStream"); } } void Stream::read_stream(int n_frames, char *buffer) const { err = Pa_ReadStream(pastream_ptr_, reinterpret_cast<void *>(buffer), n_frames); if (err != paNoError) { report_error(err, "Pa_ReadStream"); throw std::runtime_error(""); } } // Respeaker Respeaker::~Respeaker() { Pa_Terminate(); } void Respeaker::init( const std::shared_ptr<const MicrophoneConfig> &microphone_config) { if (microphone_config->microphone_model() != MicrophoneConfig::RESPEAKER) { AERROR << "Microphone driver only supports respeaker model in config file"; } err = Pa_Initialize(); if (err != paNoError) { Pa_Terminate(); report_error(err, "Pa_Initialize"); } const PaDeviceIndex device_index = get_respeaker_index(); stream_ptr_.reset(new Stream()); stream_ptr_->init_stream( microphone_config->sample_rate(), microphone_config->channel_type_size(), microphone_config->chunk(), device_index, get_format_from_width(microphone_config->sample_width())); } const PaSampleFormat Respeaker::get_format_from_width(int width, bool is_unsigned) const { switch (width) { case 1: return is_unsigned ? paUInt8 : paInt8; case 2: return paInt16; case 3: return paInt24; case 4: return paFloat32; default: break; } AERROR << "invalid width: " << width; return -1; } const PaDeviceIndex Respeaker::get_respeaker_index() const { // return index of respeaker const PaHostApiInfo *host_api_info = get_host_api_info(0); const PaDeviceInfo *device_info = nullptr; PaDeviceIndex real_index; for (PaDeviceIndex i = 0; i < host_api_info->deviceCount; ++i) { real_index = host_api_device_index_to_device_index(0, i); device_info = get_device_info(real_index); if (std::string(device_info->name).find("ReSpeaker") != std::string::npos) { return real_index; } } AERROR << "respeaker device not found"; return -1; } const PaDeviceInfo *Respeaker::get_device_info( const PaDeviceIndex index) const { const PaDeviceInfo *device_info = reinterpret_cast<const PaDeviceInfo *>(Pa_GetDeviceInfo(index)); if (!device_info) { AERROR << "internal error: invalid device index" << index; } return device_info; } const PaDeviceIndex Respeaker::host_api_device_index_to_device_index( const PaHostApiIndex host_api, const int host_api_device_index) const { // Get standard device index from host-API-specific device index PaDeviceIndex device_index = Pa_HostApiDeviceIndexToDeviceIndex(host_api, host_api_device_index); if (device_index < 0) { report_error(device_index, "Pa_HostApiDeviceIndexToDeviceIndex"); } return device_index; } const PaHostApiInfo *Respeaker::get_host_api_info( const PaHostApiIndex index) const { // Get host api info by it's index const PaHostApiInfo *pa_host_api_info = reinterpret_cast<const PaHostApiInfo *>(Pa_GetHostApiInfo(index)); if (!pa_host_api_info) { AERROR << "internal error: invalid Host Api Index " << index; } return pa_host_api_info; } void Respeaker::read_stream(int n_frames, char *buffer) const { stream_ptr_->read_stream(n_frames, buffer); } } // namespace microphone } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/microphone/respeaker.h
/****************************************************************************** * Copyright 2020 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. *****************************************************************************/ #pragma once #include <memory> #include <string> #include <google/protobuf/message.h> #include <portaudio.h> #include "cyber/cyber.h" #include "modules/drivers/microphone/proto/microphone_config.pb.h" namespace apollo { namespace drivers { namespace microphone { using apollo::drivers::microphone::config::MicrophoneConfig; /* An incomplete version of PA Stream used only for respeaker as input. * Refer to http://portaudio.com/docs/v19-doxydocs/ for more information */ class Stream { private: PaStream *pastream_ptr_; PaStreamParameters *input_parameters_ptr_; public: Stream() {} ~Stream(); void init_stream(int rate, int channels, int chunk, int input_device_index, PaSampleFormat format); void read_stream(int n_frames, char *buffer) const; }; class Respeaker { private: std::unique_ptr<Stream> stream_ptr_; const PaDeviceInfo *get_device_info(const PaDeviceIndex index) const; const PaDeviceIndex host_api_device_index_to_device_index( const PaHostApiIndex host_api, const int host_api_device_index) const; const PaHostApiInfo *get_host_api_info(const PaHostApiIndex index) const; const PaDeviceIndex get_respeaker_index() const; const PaSampleFormat get_format_from_width(int width, bool is_unsigned = true) const; public: Respeaker() {} ~Respeaker(); void init(const std::shared_ptr<const MicrophoneConfig> &microphone_config); void read_stream(int n_frames, char *buffer) const; }; } // namespace microphone } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/microphone/README.md
This serves as the audio driver folder ## Microphone Configuration * **microphone_model**: currently only support `RESPEAKER`. * **chunk**: number of frames per buffer from hardware to memory each time. * **record_seconds**: number of seconds each time. * **channel_type** * May be ASR (Audio Speech Recognition), RAW (Raw Audio Data) or Playback. * **sample_rate** * Number of frames that are recorded per second. * **sample_width** * Number of bytes per sample (1, 2, 3, or 4). For example, if there are 6 channels with 16000 Hz rate and 2 bytes width, then 4 second recording is * Number of frames: 16000 * Number of "samples": 16000 * 6 * I use the term "samples" here just to make it easy for understanding, which is seldom used in this context. * Total size: 6 × 16,000 x 4 × 2 = 768,000 bytes. You might see other metrics elsewhere as follows: * **BIT DEPTH** same to sample_width except that the unit is bit. * **BIT RATE** number of bits encoded per second (kbps or k) -- for compressed format like mp3. ## Output * Raw microphone data (cyber channel `apollo/sensor/microphone`).
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/microphone/microphone_component.h
/****************************************************************************** * Copyright 2020 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. *****************************************************************************/ #pragma once #include <atomic> #include <cmath> #include <future> #include <memory> #include <string> #include <vector> #include "cyber/cyber.h" #include "modules/common/util/message_util.h" #include "modules/drivers/microphone/proto/audio.pb.h" #include "modules/drivers/microphone/proto/microphone_config.pb.h" #include "modules/drivers/microphone/respeaker.h" namespace apollo { namespace drivers { namespace microphone { using apollo::common::util::FillHeader; using apollo::cyber::Component; using apollo::cyber::Reader; using apollo::cyber::Writer; using apollo::drivers::microphone::config::AudioData; using apollo::drivers::microphone::config::ChannelData; using apollo::drivers::microphone::config::MicrophoneConfig; class MicrophoneComponent : public Component<> { public: bool Init() override; ~MicrophoneComponent(); private: void run(); void fill_channel_data(int chunk_i); // Configuration int n_chunks_, n_channels_, chunk_, chunk_size_, n_chunk_, sample_width_; // class data std::shared_ptr<AudioData> audio_data_ptr_; std::shared_ptr<Writer<AudioData>> writer_ptr_; std::unique_ptr<Respeaker> microphone_device_ptr_; std::vector<std::string *> channel_data_ptrs_; std::shared_ptr<MicrophoneConfig> microphone_config_ptr_; char *buffer_; std::future<void> async_result_; std::atomic<bool> running_ = {false}; }; CYBER_REGISTER_COMPONENT(MicrophoneComponent) } // namespace microphone } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/microphone/BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library") load("//tools/install:install.bzl", "install") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) MICROPHONE_COPTS = ['-DMODULE_NAME=\\"microphone\\"'] cc_binary( name = "libmicrophone_component.so", linkshared = True, linkstatic = True, deps = [ ":microphone_component_lib", ], ) install( name = "install", data_dest = "drivers/addition_data/microphone", library_dest = "drivers/lib/microphone", data = [ ":runtime_data", ], targets = [ ":libmicrophone_component.so", ], deps = [":install_lib_top_level"] ) install( name = "install_lib_top_level", library_dest = "drivers/lib", targets = [ ":libmicrophone_component.so", ], ) filegroup( name = "runtime_data", srcs = glob([ "conf/*.txt", "dag/*.dag", "launch/*.launch", ]), ) cc_library( name = "microphone_component_lib", srcs = ["microphone_component.cc"], hdrs = ["microphone_component.h"], copts = MICROPHONE_COPTS, alwayslink = True, deps = [ "//cyber", "//modules/common/util:util_tool", "//modules/drivers/microphone:respeaker", "//modules/drivers/microphone/proto:audio_cc_proto", "//modules/drivers/microphone/proto:microphone_config_cc_proto", ], ) cc_library( name = "respeaker", srcs = ["respeaker.cc"], hdrs = ["respeaker.h"], copts = MICROPHONE_COPTS, deps = [ "//cyber", "//modules/drivers/microphone/proto:microphone_config_cc_proto", "@portaudio", ], ) cpplint()
0
apollo_public_repos/apollo/modules/drivers/microphone
apollo_public_repos/apollo/modules/drivers/microphone/proto/audio.proto
syntax = "proto2"; package apollo.drivers.microphone.config; import "modules/common_msgs/basic_msgs/header.proto"; import "modules/drivers/microphone/proto/microphone_config.proto"; message ChannelData { optional ChannelType channel_type = 1; optional bytes data = 2; } message AudioData { optional apollo.common.Header header = 1; optional MicrophoneConfig microphone_config = 2; repeated ChannelData channel_data = 3; }
0
apollo_public_repos/apollo/modules/drivers/microphone
apollo_public_repos/apollo/modules/drivers/microphone/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") package(default_visibility = ["//visibility:public"]) cc_proto_library( name = "audio_cc_proto", deps = [ ":audio_proto", ], ) proto_library( name = "audio_proto", srcs = ["audio.proto"], deps = [ "//modules/common_msgs/basic_msgs:header_proto", ":microphone_config_proto", ], ) py_proto_library( name = "audio_py_pb2", deps = [ ":audio_proto", "//modules/common_msgs/basic_msgs:header_py_pb2", ":microphone_config_py_pb2", ], ) cc_proto_library( name = "microphone_config_cc_proto", deps = [ ":microphone_config_proto", ], ) proto_library( name = "microphone_config_proto", srcs = ["microphone_config.proto"], ) py_proto_library( name = "microphone_config_py_pb2", deps = [ ":microphone_config_proto", ], )
0
apollo_public_repos/apollo/modules/drivers/microphone
apollo_public_repos/apollo/modules/drivers/microphone/proto/microphone_config.proto
syntax = "proto2"; package apollo.drivers.microphone.config; enum ChannelType { UNKNOWN = 0; ASR = 1; // Automatic Speech Recognition RAW = 2; PLAYBACK = 3; } message MicrophoneConfig { enum MicrophoneModel { UNKNOWN = 0; RESPEAKER = 1; } optional MicrophoneModel microphone_model = 2; optional int32 chunk = 3; optional float sample_rate = 4; optional float record_seconds = 5; optional int32 sample_width = 6; // in bytes optional string channel_name = 7; optional string frame_id = 8; optional float mic_distance = 9; repeated ChannelType channel_type = 1; }
0
apollo_public_repos/apollo/modules/drivers/microphone
apollo_public_repos/apollo/modules/drivers/microphone/launch/microphone.launch
<cyber> <module> <name>microphone</name> <dag_conf>/apollo/modules/drivers/microphone/dag/microphone.dag</dag_conf> <process_name>respeaker</process_name> </module> </cyber>
0