Skip to main content

protocol_only/
protocol_only.rs

1// Copyright 2026 mjbots Robotic Systems, LLC.  info@mjbots.com
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! This example demonstrates how to use the low-level moteus-protocol
16//! crate to construct and parse CAN-FD frames without any transport.
17//!
18//! This is useful for embedded systems or custom transport implementations.
19//!
20//! Usage:
21//!   tools/bazel run //lib/rust:protocol_only
22
23use moteus_protocol::command::{
24    BrakeCommand, CurrentCommand, CurrentFormat, PositionCommand, PositionFormat, StopCommand,
25};
26use moteus_protocol::query::{QueryFormat, QueryResult};
27use moteus_protocol::{calculate_arbitration_id, parse_arbitration_id, CanFdFrame, Resolution};
28
29fn main() {
30    println!("=== moteus-protocol Example ===\n");
31
32    // Example 1: Create a stop command
33    println!("1. Creating a stop command for servo ID 1:");
34    let mut stop_frame = CanFdFrame::new();
35    stop_frame.arbitration_id = calculate_arbitration_id(0, 1, 0, true);
36    StopCommand::serialize(&mut stop_frame);
37    print_frame(&stop_frame);
38
39    // Example 2: Create a position command using builder pattern
40    println!("\n2. Creating a position command:");
41    let mut pos_frame = CanFdFrame::new();
42    pos_frame.arbitration_id = calculate_arbitration_id(0, 1, 0, true);
43
44    let pos_cmd = PositionCommand::new()
45        .position(0.5) // 0.5 revolutions
46        .velocity(1.0) // 1.0 rev/s
47        .kp_scale(1.0)
48        .kd_scale(1.0);
49    let pos_format = PositionFormat::default();
50
51    pos_cmd.serialize(&mut pos_frame, &pos_format);
52    print_frame(&pos_frame);
53
54    // Example 3: Create a query-only command
55    println!("\n3. Creating a query-only command:");
56    let mut query_frame = CanFdFrame::new();
57    query_frame.arbitration_id = calculate_arbitration_id(0, 1, 0, true);
58
59    let mut custom_query = QueryFormat::default();
60    custom_query.position = Resolution::Float; // Request full precision
61    custom_query.velocity = Resolution::Float;
62    custom_query.torque = Resolution::Float;
63
64    let reply_size = custom_query.serialize(&mut query_frame);
65    print_frame(&query_frame);
66    println!("  Expected reply size: {} bytes", reply_size);
67
68    // Example 4: Parse a simulated response
69    println!("\n4. Parsing a simulated response:");
70
71    // Construct a fake response frame as if from servo ID 1
72    let mut response = CanFdFrame::new();
73    response.arbitration_id = calculate_arbitration_id(1, 0, 0, false);
74
75    // Manually construct response data:
76    // This would normally come from the CAN bus
77    // Format: [reply header] [register] [values...]
78    response.data[0] = 0x21; // Reply Int8, count=1
79    response.data[1] = 0x00; // Register 0 (Mode)
80    response.data[2] = 0x0A; // Mode = Position (10)
81    response.data[3] = 0x2D; // Reply Float (0x2c), count=1 (0x01)
82    response.data[4] = 0x01; // Register 1 (Position)
83    response.data[5] = 0x00; // Position as f32 (0.5)
84    response.data[6] = 0x00;
85    response.data[7] = 0x00;
86    response.data[8] = 0x3F;
87    response.size = 9;
88
89    let result = QueryResult::parse(&response);
90    println!("  Parsed QueryResult:");
91    println!("    Mode: {:?}", result.mode);
92    println!("    Position: {:.4} rev", result.position);
93    println!("    Velocity: {:.4} rev/s", result.velocity);
94    println!("    Torque: {:.4} Nm", result.torque);
95
96    // Example 5: Create a current (torque) command using builder pattern
97    println!("\n5. Creating a current command:");
98    let mut current_frame = CanFdFrame::new();
99    current_frame.arbitration_id = calculate_arbitration_id(0, 1, 0, true);
100
101    let current_cmd = CurrentCommand::new().d_current(0.0).q_current(0.5);
102    current_cmd.serialize(&mut current_frame, &CurrentFormat::default());
103    print_frame(&current_frame);
104
105    // Example 6: Create a brake command
106    println!("\n6. Creating a brake command:");
107    let mut brake_frame = CanFdFrame::new();
108    brake_frame.arbitration_id = calculate_arbitration_id(0, 1, 0, true);
109
110    BrakeCommand::serialize(&mut brake_frame);
111    print_frame(&brake_frame);
112    println!("  Mode byte: {} (Brake=15)", brake_frame.data[2]);
113
114    println!("\n=== Done ===");
115}
116
117fn print_frame(frame: &CanFdFrame) {
118    let (source, destination, _prefix) = parse_arbitration_id(frame.arbitration_id);
119    let reply_required = frame.arbitration_id & 0x8000 != 0;
120    print!("  Arbitration ID: 0x{:04X}", frame.arbitration_id);
121    println!(" (dest={}, source={})", destination, source);
122    print!("  Data ({} bytes): ", frame.size);
123    for i in 0..frame.size as usize {
124        print!("{:02X} ", frame.data[i]);
125    }
126    println!();
127    println!("  Reply required: {}", reply_required);
128}