Skip to content

Commit 6c2d546

Browse files
committed
refactor: Improve code readability by standardizing formatting and spacing in Dynamixel header and source files
1 parent 867ddff commit 6c2d546

File tree

5 files changed

+136
-71
lines changed

5 files changed

+136
-71
lines changed

include/dynamixel_hardware_interface/dynamixel/dynamixel.hpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,7 @@ class Dynamixel
213213

214214
DxlError ReadDxlModelFile(uint8_t id, uint16_t model_num);
215215
DxlError ReadDxlModelFile(uint8_t id, uint16_t model_num, uint8_t firmware_version);
216-
DxlError ReadFirmwareVersion(uint8_t id, uint8_t& firmware_version);
216+
DxlError ReadFirmwareVersion(uint8_t id, uint8_t & firmware_version);
217217

218218
void SetCommId(uint8_t id, uint8_t comm_id) {comm_id_[id] = comm_id;}
219219

include/dynamixel_hardware_interface/dynamixel/dynamixel_info.hpp

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,10 +63,14 @@ class DynamixelInfo
6363
std::string dxl_model_file_dir;
6464

6565
// Firmware version-aware model file selection
66-
std::string SelectModelFileByFirmwareVersion(const std::string& base_model_name, uint8_t firmware_version);
67-
bool IsFirmwareSpecificModelFile(const std::string& filename);
68-
uint8_t ExtractFirmwareVersionFromFilename(const std::string& filename);
69-
bool ShouldUseFirmwareSpecificModel(uint8_t device_firmware_version, uint8_t model_firmware_version);
66+
std::string SelectModelFileByFirmwareVersion(
67+
const std::string & base_model_name,
68+
uint8_t firmware_version);
69+
bool IsFirmwareSpecificModelFile(const std::string & filename);
70+
uint8_t ExtractFirmwareVersionFromFilename(const std::string & filename);
71+
bool ShouldUseFirmwareSpecificModel(
72+
uint8_t device_firmware_version,
73+
uint8_t model_firmware_version);
7074

7175
public:
7276
// Id, Control table

scripts/check_model_file_formatting.py

Lines changed: 76 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,22 @@
11
#!/usr/bin/env python3
2+
#
3+
# Copyright 2025 ROBOTIS CO., LTD.
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the 'License');
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an 'AS IS' BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
#
17+
# Author: Woojin Wie
18+
19+
220
"""
321
Script to check formatting of Dynamixel model files.
422
@@ -15,10 +33,10 @@
1533
--verbose Show detailed information about each file
1634
"""
1735

36+
import argparse
1837
import os
1938
import sys
20-
import argparse
21-
import re
39+
2240

2341
def check_file_formatting(file_path, fix=False, verbose=False):
2442
"""
@@ -36,19 +54,19 @@ def check_file_formatting(file_path, fix=False, verbose=False):
3654
'trailing_spaces': [],
3755
'no_eof_newline': False,
3856
'empty_lines_at_end': 0,
39-
'fixed': []
57+
'fixed': [],
4058
}
4159

4260
try:
4361
with open(file_path, 'r', encoding='utf-8') as f:
4462
lines = f.readlines()
4563
except Exception as e:
46-
print(f"Error reading {file_path}: {e}")
64+
print(f'Error reading {file_path}: {e}')
4765
return issues
4866

4967
if not lines:
5068
if verbose:
51-
print(f" {file_path}: Empty file")
69+
print(f' {file_path}: Empty file')
5270
return issues
5371

5472
# Check for trailing spaces
@@ -74,68 +92,80 @@ def check_file_formatting(file_path, fix=False, verbose=False):
7492
issues['empty_lines_at_end'] = empty_lines_at_end
7593

7694
# Fix issues if requested
77-
if fix and (issues['trailing_spaces'] or issues['no_eof_newline'] or issues['empty_lines_at_end'] > 1):
95+
if fix and (
96+
issues['trailing_spaces']
97+
or issues['no_eof_newline']
98+
or issues['empty_lines_at_end'] > 1
99+
):
78100
fixed_lines = []
79101

80102
for i, line in enumerate(lines):
81103
# Remove trailing spaces but preserve newline
82104
if i + 1 in issues['trailing_spaces']:
83105
line_content = line.rstrip('\n')
84106
fixed_lines.append(line_content.rstrip() + '\n')
85-
issues['fixed'].append(f"Line {i + 1}: Removed trailing spaces")
107+
issues['fixed'].append(
108+
f'Line {i + 1}: Removed trailing spaces')
86109
else:
87110
fixed_lines.append(line)
88111

89112
# Ensure proper EOF
90113
if issues['no_eof_newline']:
91114
if fixed_lines and not fixed_lines[-1].endswith('\n'):
92115
fixed_lines[-1] = fixed_lines[-1] + '\n'
93-
issues['fixed'].append("Added EOF newline")
116+
issues['fixed'].append('Added EOF newline')
94117

95118
# Remove excessive empty lines at the end
96119
if issues['empty_lines_at_end'] > 1:
97120
# Remove all empty lines at the end, then add one
98121
while fixed_lines and fixed_lines[-1].strip() == '':
99122
fixed_lines.pop()
100123
fixed_lines.append('\n') # Add single newline at end
101-
issues['fixed'].append(f"Removed {issues['empty_lines_at_end'] - 1} excessive empty lines at end")
124+
issues['fixed'].append(
125+
f'Removed {issues["empty_lines_at_end"] - 1} excessive empty lines at end'
126+
)
102127

103128
# Write fixed file
104129
try:
105130
with open(file_path, 'w', encoding='utf-8') as f:
106131
f.writelines(fixed_lines)
107132
except Exception as e:
108-
print(f"Error writing {file_path}: {e}")
133+
print(f'Error writing {file_path}: {e}')
109134
return issues
110135

111136
return issues
112137

138+
113139
def main():
114-
"""Main function."""
140+
"""Run the formatting check or fix process for Dynamixel model files."""
115141
parser = argparse.ArgumentParser(
116-
description="Check formatting of Dynamixel model files",
142+
description='Check formatting of Dynamixel model files',
117143
formatter_class=argparse.RawDescriptionHelpFormatter,
118144
epilog="""
119145
Examples:
120146
python3 check_model_file_formatting.py
121147
python3 check_model_file_formatting.py --fix
122148
python3 check_model_file_formatting.py --verbose
123149
python3 check_model_file_formatting.py --fix --verbose
124-
"""
150+
""",
125151
)
126152

127-
parser.add_argument('--fix', action='store_true',
128-
help='Automatically fix formatting issues')
129-
parser.add_argument('--verbose', action='store_true',
130-
help='Show detailed information about each file')
153+
parser.add_argument(
154+
'--fix', action='store_true', help='Automatically fix formatting issues'
155+
)
156+
parser.add_argument(
157+
'--verbose',
158+
action='store_true',
159+
help='Show detailed information about each file',
160+
)
131161

132162
args = parser.parse_args()
133163

134164
# Find model files
135-
model_dir = "param/dxl_model"
165+
model_dir = 'param/dxl_model'
136166
if not os.path.exists(model_dir):
137167
print(f"Error: Model directory '{model_dir}' not found.")
138-
print("Please run this script from the dynamixel_hardware_interface directory.")
168+
print('Please run this script from the dynamixel_hardware_interface directory.')
139169
sys.exit(1)
140170

141171
model_files = []
@@ -144,12 +174,12 @@ def main():
144174
model_files.append(os.path.join(model_dir, file))
145175

146176
if not model_files:
147-
print("No .model files found.")
177+
print('No .model files found.')
148178
sys.exit(0)
149179

150-
print(f"Checking {len(model_files)} model files...")
180+
print(f'Checking {len(model_files)} model files...')
151181
if args.fix:
152-
print("Auto-fix mode enabled.")
182+
print('Auto-fix mode enabled.')
153183
print()
154184

155185
total_issues = 0
@@ -159,45 +189,53 @@ def main():
159189
file_name = os.path.basename(file_path)
160190
issues = check_file_formatting(file_path, args.fix, args.verbose)
161191

162-
has_issues = (issues['trailing_spaces'] or
163-
issues['no_eof_newline'] or
164-
issues['empty_lines_at_end'] > 1)
192+
has_issues = (
193+
issues['trailing_spaces']
194+
or issues['no_eof_newline']
195+
or issues['empty_lines_at_end'] > 1
196+
)
165197

166198
if has_issues:
167199
files_with_issues += 1
168-
print(f"{file_name}")
200+
print(f'{file_name}')
169201

170202
if issues['trailing_spaces']:
171-
print(f" Trailing spaces on lines: {', '.join(map(str, issues['trailing_spaces']))}")
203+
print(
204+
f' Trailing spaces on lines: \
205+
{", ".join(map(str, issues["trailing_spaces"]))}'
206+
)
172207
total_issues += len(issues['trailing_spaces'])
173208

174209
if issues['no_eof_newline']:
175-
print(" Missing EOF newline")
210+
print(' Missing EOF newline')
176211
total_issues += 1
177212

178213
if issues['empty_lines_at_end'] > 1:
179-
print(f" {issues['empty_lines_at_end']} empty lines at end of file")
214+
print(
215+
f' {issues["empty_lines_at_end"]} empty lines at end of file')
180216
total_issues += 1
181217

182218
if args.fix and issues['fixed']:
183-
print(" Fixed:")
219+
print(' Fixed:')
184220
for fix in issues['fixed']:
185-
print(f" - {fix}")
221+
print(f' - {fix}')
186222

187223
print()
188224
elif args.verbose:
189-
print(f"{file_name} - No issues found")
225+
print(f'{file_name} - No issues found')
190226

191227
# Summary
192-
print("=" * 50)
228+
print('=' * 50)
193229
if files_with_issues == 0:
194-
print("🎉 All model files are properly formatted!")
230+
print('🎉 All model files are properly formatted!')
195231
else:
196-
print(f"Found {total_issues} formatting issues in {files_with_issues} files.")
232+
print(
233+
f'Found {total_issues} formatting issues in {files_with_issues} files.')
197234
if not args.fix:
198-
print("Run with --fix to automatically fix these issues.")
235+
print('Run with --fix to automatically fix these issues.')
199236

200237
return 0 if files_with_issues == 0 else 1
201238

202-
if __name__ == "__main__":
203-
sys.exit(main())
239+
240+
if __name__ == '__main__':
241+
sys.exit(main())

src/dynamixel/dynamixel.cpp

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -102,13 +102,14 @@ DxlError Dynamixel::ReadDxlModelFile(uint8_t id, uint16_t model_num, uint8_t fir
102102
}
103103
}
104104

105-
DxlError Dynamixel::ReadFirmwareVersion(uint8_t id, uint8_t& firmware_version)
105+
DxlError Dynamixel::ReadFirmwareVersion(uint8_t id, uint8_t & firmware_version)
106106
{
107107
uint32_t fw_version_data;
108108
DxlError result = ReadItem(id, "Firmware Version", fw_version_data);
109109
if (result == DxlError::OK) {
110110
firmware_version = static_cast<uint8_t>(fw_version_data);
111-
// fprintf(stderr, "[ReadFirmwareVersion][ID:%03d] Firmware Version: %d\n", id, firmware_version);
111+
// fprintf(stderr, "[ReadFirmwareVersion][ID:%03d] Firmware Version: %d\n",
112+
// id, firmware_version);
112113
} else {
113114
fprintf(stderr, "[ReadFirmwareVersion][ID:%03d] Failed to read firmware version\n", id);
114115
}
@@ -209,7 +210,8 @@ DxlError Dynamixel::InitDxlComm(
209210
return DxlError::DXL_HARDWARE_ERROR;
210211
} else {
211212
std::string model_name = dxl_info_.GetModelName(dxl_model_number);
212-
fprintf(stderr, " - Ping succeeded. Dynamixel model number : %d (%s)\n", dxl_model_number, model_name.c_str());
213+
fprintf(stderr, " - Ping succeeded. Dynamixel model number : %d (%s)\n", dxl_model_number,
214+
model_name.c_str());
213215
}
214216

215217
// First, read the model file to get the control table structure
@@ -224,11 +226,13 @@ DxlError Dynamixel::InitDxlComm(
224226
uint8_t firmware_version = 0;
225227
DxlError fw_result = ReadFirmwareVersion(it_id, firmware_version);
226228
if (fw_result == DxlError::OK && firmware_version > 0) {
227-
// fprintf(stderr, "[InitDxlComm][ID:%03d] Reloading model file with firmware version %d\n", it_id, firmware_version);
229+
// fprintf(stderr, "[InitDxlComm][ID:%03d] Reloading model file with firmware version %d\n",
230+
// it_id, firmware_version);
228231
try {
229232
dxl_info_.ReadDxlModelFile(it_id, dxl_model_number, firmware_version);
230233
} catch (const std::exception & e) {
231-
fprintf(stderr, "[InitDxlComm][ID:%03d] Error reading firmware-specific model file: %s\n", it_id, e.what());
234+
fprintf(stderr, "[InitDxlComm][ID:%03d] Error reading firmware-specific model file: %s\n",
235+
it_id, e.what());
232236
// Continue with the base model file if firmware-specific file fails
233237
}
234238
}

0 commit comments

Comments
 (0)