Skip to content

Commit

Permalink
feat: Replace println with proper logging (#45)
Browse files Browse the repository at this point in the history
for better filtering etc.
  • Loading branch information
philipp-caspers authored Sep 24, 2024
1 parent 1a6f9bb commit 9141ffe
Show file tree
Hide file tree
Showing 8 changed files with 118 additions and 15 deletions.
94 changes: 93 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ builtin_interfaces = { version = "1.2.1" }
voraus_interfaces = { version = "0.1.0" }
rclrs = { version = "0.4.1" }
rosidl_runtime_rs = { version = "0.4.1" }
log = "0.4.22"
env_logger = "0.11.5"

[dev-dependencies]
rclrs = { version = "0.4.1" }
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ Run `cargo build --release`
### Run the voraus-ros-bridge

Run `cargo run --release`
In order to get debug log output, run `RUST_LOG=DEBUG cargo run --release`

## via ROS:

Expand Down
5 changes: 3 additions & 2 deletions examples/ros2/simple-subscriber.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use log::debug;
use rclrs::{create_node, Context, Node, RclrsError, Subscription, QOS_PROFILE_DEFAULT};
use sensor_msgs::msg::JointState as JointStateMsg;
use std::{
Expand Down Expand Up @@ -37,13 +38,13 @@ impl Subscriber {
}
fn callback(&self, msg: JointStateMsg) {
self.num_messages.fetch_add(1, Ordering::SeqCst);
println!(
debug!(
"[{}] I heard: '{:?}' with timestamp {}.",
self.node.name(),
msg.position,
msg.header.stamp.nanosec
);
println!(
debug!(
"[{}] (Got {} messages so far)",
self.node.name(),
self.num_messages.load(Ordering::SeqCst)
Expand Down
9 changes: 6 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
mod simple_opc_ua_subscriber;

use env_logger::{Builder, Env};
use log::debug;
use opcua::types::Variant;
use rclrs::{create_node, Context, RclrsError};
use ros_service_server::handle_service;
Expand All @@ -12,6 +14,9 @@ mod ros_service_server;
use ros_publisher::{create_joint_state_msg, RosPublisher};

fn main() -> Result<(), RclrsError> {
Builder::from_env(Env::default().default_filter_or("info"))
.filter_module("opcua", log::LevelFilter::Warn)
.init();
let context = Context::new(env::args()).unwrap();
let node = create_node(&context, "voraus_bridge_node")?;
let node_copy = Arc::clone(&node);
Expand All @@ -20,8 +25,6 @@ fn main() -> Result<(), RclrsError> {
let _server = node_copy
.create_service::<voraus_interfaces::srv::Voraus, _>("add_two_ints", handle_service)?;

opcua::console_logging::init();

let mut simple_subscriber = SimpleSubscriber::new("opc.tcp://127.0.0.1:4855");
let Ok(_connection_result) = simple_subscriber.connect() else {
panic!("Connection could not be established, but is required.");
Expand All @@ -30,7 +33,7 @@ fn main() -> Result<(), RclrsError> {
let callback = {
let provider = Arc::clone(&joint_state_publisher);
move |x: Variant| {
println!("Value = {:?}", &x);
debug!("Value = {:?}", &x);
let mut data_value: Vec<f64> = vec![];
match x {
Variant::Array(unwrapped) => {
Expand Down
4 changes: 3 additions & 1 deletion src/ros_service_server.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use log::debug;

pub fn handle_service(
_request_header: &rclrs::rmw_request_id_t,
request: voraus_interfaces::srv::Voraus_Request,
) -> voraus_interfaces::srv::Voraus_Response {
println!("request: {} + {}", request.a, request.b);
debug!("request: {} + {}", request.a, request.b);
voraus_interfaces::srv::Voraus_Response {
sum: request.a + request.b,
}
Expand Down
11 changes: 6 additions & 5 deletions src/simple_opc_ua_subscriber.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::sync::Arc;

use log::{debug, error};
use opcua::client::prelude::{
Client, ClientBuilder, DataChangeCallback, IdentityToken, MonitoredItem, MonitoredItemService,
Session, SubscriptionService,
Expand Down Expand Up @@ -72,8 +73,8 @@ impl SimpleSubscriber {
if self.session.is_none() {
panic!("Not connected. Can't create subscriptions.");
}
println!(
"Creating a subscription for ns={};{} to indirectly call the callback every {}ms.",
debug!(
"Creating a subscription for ns={};{} to indirectly call the callback every {} ms.",
namespace, node_id, period_ms
);
let cloned_session_lock = self.session.clone().unwrap();
Expand All @@ -94,13 +95,13 @@ impl SimpleSubscriber {
priority,
publishing_enabled,
DataChangeCallback::new(move |changed_monitored_items| {
println!("Data change from server:");
debug!("Data change from server:");
changed_monitored_items
.iter()
.for_each(|item| callback(extract_value(item)));
}),
)?;
println!("Created a subscription with id = {}", subscription_id);
debug!("Created a subscription with id = {}", subscription_id);

// Create some monitored items
let items_to_create: Vec<MonitoredItemCreateRequest> = [node_id]
Expand All @@ -120,7 +121,7 @@ impl SimpleSubscriber {
match self.session {
Some(session) => Session::run(session),
None => {
eprintln!("Could not run inexistent session.");
error!("Could not run inexistent session.");
}
}
}
Expand Down
7 changes: 4 additions & 3 deletions tests/test_simple_opc_ua_subscriber.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,16 @@ async fn test_simple_subscriber_receives_data_changes() {

let mut client_process = TokioCommand::new("cargo")
.arg("run")
.env("RUST_LOG", "DEBUG")
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("Failed to start client");

let client_stdout = client_process
.stdout
.stderr
.take()
.expect("Failed to capture client stdout");
.expect("Failed to capture client stderr");
let mut reader = BufReader::new(client_stdout).lines();

let mut found_ticks_since_launch_changed_times = 0u32;
Expand All @@ -39,7 +40,7 @@ async fn test_simple_subscriber_receives_data_changes() {
.await
.expect("Failed to read line from client")
{
println!("Subscriber stdout: {}", line);
println!("Subscriber stderr: {}", line);
if line.contains("Value = Array(Array { value_type: Double") {
found_ticks_since_launch_changed_times += 1;
if found_ticks_since_launch_changed_times == expected_changed_times {
Expand Down

0 comments on commit 9141ffe

Please sign in to comment.