Initial commit

This commit is contained in:
2026-07-27 13:51:19 +08:00
commit 7bec56ca51
5408 changed files with 1126933 additions and 0 deletions
+205
View File
@@ -0,0 +1,205 @@
cmake_minimum_required(VERSION 3.0.2)
project(bms_driver_mingnuo)
## Compile as C++11, supported in ROS Kinetic and newer
# add_compile_options(-std=c++11)
## Find catkin macros and libraries
## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz)
## is used, also find other catkin packages
find_package(catkin REQUIRED COMPONENTS
rospy
serial
)
## System dependencies are found with CMake's conventions
# find_package(Boost REQUIRED COMPONENTS system)
## Uncomment this if the package has a setup.py. This macro ensures
## modules and global scripts declared therein get installed
## See http://ros.org/doc/api/catkin/html/user_guide/setup_dot_py.html
# catkin_python_setup()
################################################
## Declare ROS messages, services and actions ##
################################################
## To declare and build messages, services or actions from within this
## package, follow these steps:
## * Let MSG_DEP_SET be the set of packages whose message types you use in
## your messages/services/actions (e.g. std_msgs, actionlib_msgs, ...).
## * In the file package.xml:
## * add a build_depend tag for "message_generation"
## * add a build_depend and a exec_depend tag for each package in MSG_DEP_SET
## * If MSG_DEP_SET isn't empty the following dependency has been pulled in
## but can be declared for certainty nonetheless:
## * add a exec_depend tag for "message_runtime"
## * In this file (CMakeLists.txt):
## * add "message_generation" and every package in MSG_DEP_SET to
## find_package(catkin REQUIRED COMPONENTS ...)
## * add "message_runtime" and every package in MSG_DEP_SET to
## catkin_package(CATKIN_DEPENDS ...)
## * uncomment the add_*_files sections below as needed
## and list every .msg/.srv/.action file to be processed
## * uncomment the generate_messages entry below
## * add every package in MSG_DEP_SET to generate_messages(DEPENDENCIES ...)
## Generate messages in the 'msg' folder
# add_message_files(
# FILES
# Message1.msg
# Message2.msg
# )
## Generate services in the 'srv' folder
# add_service_files(
# FILES
# Service1.srv
# Service2.srv
# )
## Generate actions in the 'action' folder
# add_action_files(
# FILES
# Action1.action
# Action2.action
# )
## Generate added messages and services with any dependencies listed here
# generate_messages(
# DEPENDENCIES
# std_msgs # Or other packages containing msgs
# )
################################################
## Declare ROS dynamic reconfigure parameters ##
################################################
## To declare and build dynamic reconfigure parameters within this
## package, follow these steps:
## * In the file package.xml:
## * add a build_depend and a exec_depend tag for "dynamic_reconfigure"
## * In this file (CMakeLists.txt):
## * add "dynamic_reconfigure" to
## find_package(catkin REQUIRED COMPONENTS ...)
## * uncomment the "generate_dynamic_reconfigure_options" section below
## and list every .cfg file to be processed
## Generate dynamic reconfigure parameters in the 'cfg' folder
# generate_dynamic_reconfigure_options(
# cfg/DynReconf1.cfg
# cfg/DynReconf2.cfg
# )
###################################
## catkin specific configuration ##
###################################
## The catkin_package macro generates cmake config files for your package
## Declare things to be passed to dependent projects
## INCLUDE_DIRS: uncomment this if your package contains header files
## LIBRARIES: libraries you create in this project that dependent projects also need
## CATKIN_DEPENDS: catkin_packages dependent projects also need
## DEPENDS: system dependencies of this project that dependent projects also need
catkin_package(
# INCLUDE_DIRS include
# LIBRARIES bms_driver_mingnuo
# CATKIN_DEPENDS rospy serial
# DEPENDS system_lib
)
###########
## Build ##
###########
## Specify additional locations of header files
## Your package locations should be listed before other locations
include_directories(
# include
${catkin_INCLUDE_DIRS}
)
## Declare a C++ library
# add_library(${PROJECT_NAME}
# src/${PROJECT_NAME}/bms_driver_mingnuo.cpp
# )
## Add cmake target dependencies of the library
## as an example, code may need to be generated before libraries
## either from message generation or dynamic reconfigure
# add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
## Declare a C++ executable
## With catkin_make all packages are built within a single CMake context
## The recommended prefix ensures that target names across packages don't collide
# add_executable(${PROJECT_NAME}_node src/bms_driver_mingnuo_node.cpp)
## Rename C++ executable without prefix
## The above recommended prefix causes long target names, the following renames the
## target back to the shorter version for ease of user use
## e.g. "rosrun someones_pkg node" instead of "rosrun someones_pkg someones_pkg_node"
# set_target_properties(${PROJECT_NAME}_node PROPERTIES OUTPUT_NAME node PREFIX "")
## Add cmake target dependencies of the executable
## same as for the library above
# add_dependencies(${PROJECT_NAME}_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
## Specify libraries to link a library or executable target against
# target_link_libraries(${PROJECT_NAME}_node
# ${catkin_LIBRARIES}
# )
#############
## Install ##
#############
# all install targets should use catkin DESTINATION variables
# See http://ros.org/doc/api/catkin/html/adv_user_guide/variables.html
## Mark executable scripts (Python etc.) for installation
## in contrast to setup.py, you can choose the destination
# catkin_install_python(PROGRAMS
# scripts/my_python_script
# DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
# )
## Mark executables for installation
## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_executables.html
# install(TARGETS ${PROJECT_NAME}_node
# RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
# )
## Mark libraries for installation
## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html
# install(TARGETS ${PROJECT_NAME}
# ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
# LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
# RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
# )
## Mark cpp header files for installation
# install(DIRECTORY include/${PROJECT_NAME}/
# DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
# FILES_MATCHING PATTERN "*.h"
# PATTERN ".svn" EXCLUDE
# )
## Mark other files for installation (e.g. launch and bag files, etc.)
# install(FILES
# # myfile1
# # myfile2
# DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
# )
#############
## Testing ##
#############
## Add gtest based cpp test target and link libraries
# catkin_add_gtest(${PROJECT_NAME}-test test/test_bms_driver_mingnuo.cpp)
# if(TARGET ${PROJECT_NAME}-test)
# target_link_libraries(${PROJECT_NAME}-test ${PROJECT_NAME})
# endif()
## Add folders to be run by python nosetests
# catkin_add_nosetests(test)
@@ -0,0 +1,7 @@
<launch>
<node name="bms_driver_mingnuo" pkg="bms_driver_mingnuo" type="bms_driver_node.py" output="screen">
<!-- 仅保留可能需要动态调整的参数 -->
<param name="port" value="/dev/ttyS2" />
<param name="baudrate" value="9600" />
</node>
</launch>
+65
View File
@@ -0,0 +1,65 @@
<?xml version="1.0"?>
<package format="2">
<name>bms_driver_mingnuo</name>
<version>0.0.0</version>
<description>The bms_driver_mingnuo package</description>
<!-- One maintainer tag required, multiple allowed, one person per tag -->
<!-- Example: -->
<!-- <maintainer email="jane.doe@example.com">Jane Doe</maintainer> -->
<maintainer email="dreamdeck@todo.todo">dreamdeck</maintainer>
<!-- One license tag required, multiple allowed, one license per tag -->
<!-- Commonly used license strings: -->
<!-- BSD, MIT, Boost Software License, GPLv2, GPLv3, LGPLv2.1, LGPLv3 -->
<license>TODO</license>
<!-- Url tags are optional, but multiple are allowed, one per tag -->
<!-- Optional attribute type can be: website, bugtracker, or repository -->
<!-- Example: -->
<!-- <url type="website">http://wiki.ros.org/bms_driver_mingnuo</url> -->
<!-- Author tags are optional, multiple are allowed, one per tag -->
<!-- Authors do not have to be maintainers, but could be -->
<!-- Example: -->
<!-- <author email="jane.doe@example.com">Jane Doe</author> -->
<!-- The *depend tags are used to specify dependencies -->
<!-- Dependencies can be catkin packages or system dependencies -->
<!-- Examples: -->
<!-- Use depend as a shortcut for packages that are both build and exec dependencies -->
<!-- <depend>roscpp</depend> -->
<!-- Note that this is equivalent to the following: -->
<!-- <build_depend>roscpp</build_depend> -->
<!-- <exec_depend>roscpp</exec_depend> -->
<!-- Use build_depend for packages you need at compile time: -->
<!-- <build_depend>message_generation</build_depend> -->
<!-- Use build_export_depend for packages you need in order to build against this package: -->
<!-- <build_export_depend>message_generation</build_export_depend> -->
<!-- Use buildtool_depend for build tool packages: -->
<!-- <buildtool_depend>catkin</buildtool_depend> -->
<!-- Use exec_depend for packages you need at runtime: -->
<!-- <exec_depend>message_runtime</exec_depend> -->
<!-- Use test_depend for packages you need only for testing: -->
<!-- <test_depend>gtest</test_depend> -->
<!-- Use doc_depend for packages you need only for building documentation: -->
<!-- <doc_depend>doxygen</doc_depend> -->
<buildtool_depend>catkin</buildtool_depend>
<build_depend>rospy</build_depend>
<build_depend>serial</build_depend>
<build_export_depend>rospy</build_export_depend>
<build_export_depend>serial</build_export_depend>
<exec_depend>rospy</exec_depend>
<exec_depend>serial</exec_depend>
<!-- The export tag contains other, unspecified, tags -->
<export>
<!-- Other tools can request additional information be placed here -->
</export>
</package>
+52
View File
@@ -0,0 +1,52 @@
/sensor/battery_state话题格式解析
---
header:
seq: 527
stamp:
secs: 0
nsecs: 0
frame_id: ''
voltage: 53.79999923706055 #电池电压V
temperature: 0.0 #电池温度
current: 0.0 #电池电流A
charge: 0.0
capacity: 0.0
design_capacity: 0.0
percentage: 100.0 #电池电量百分比
power_supply_status: 0 #充电状态 1:在充电 0:未在充电
power_supply_health: 0 #报警信息1 0:表示正常 非0:有报警
power_supply_technology: 0 #报警信息2 0:表示正常 非0:有报警
present: False
cell_voltage: []
cell_temperature: []
location: ''
serial_number: ''
---
报警信息1 power_supply_health 8位数据解析
二进制位 描述 地址
D0 0表示正常 0
D1 1表示故障 1
D2 1表示充电过流 2
D3 1表示放电过流 3
D4 1表示短路保护 4
D5 1表示充电高温保护 5
D6 1表示放电高温保护 6
D7 1表示充电低温保护 7
报警信息2 power_supply_technology 8位数据解析
二进制位 描述 地址
D0 1表示放电低温保护 0
D1 1表示充电 MOS 损坏 1
D2 1表示放电 MOS 损坏 2
D3 1表示内部通讯异常 3
D4 1表示过充电压保护 4
D5 1表示过放电压保护 5
D6 6
D7 7
@@ -0,0 +1,173 @@
#!/usr/bin/env python3
import rospy
import serial
import binascii
import time
from std_msgs.msg import String
from sensor_msgs.msg import BatteryState
class BMSDriverNode:
def __init__(self):
rospy.init_node('bms_driver_mingnuo', anonymous=False)
self.port = rospy.get_param('~port', '/dev/ttyUSB0')
self.baudrate = rospy.get_param('~baudrate', 9600)
self.timeout = 0.5
self.battery_cmd = b'\x01\x03\x00\x00\x00\x1E\xC5\xC2' # 电量查询指令
self.alarm_cmd = b'\x01\x01\x00\x00\x00\x34\x3D\xDD' # 报警查询指令
self.polling_rate = 1.0
try:
self.ser = serial.Serial(
port=self.port,
baudrate=self.baudrate,
timeout=self.timeout,
parity='N',
stopbits=1,
bytesize=8
)
rospy.loginfo(f"Successfully connected to BMS: {self.port} @ {self.baudrate}bps")
except serial.SerialException as e:
rospy.logerr(f"Failed to connect to BMS: {e}")
raise
# 初始化全局消息对象
self.global_msg = BatteryState()
self.battery_pub = rospy.Publisher('/sensor/battery_state', BatteryState, queue_size=10)
self.rate = rospy.Rate(self.polling_rate)
def update_battery_data(self, hex_data):
"""更新全局消息中的电池数据"""
try:
# if len(hex_data) < 65:
# rospy.logwarn(f"Battery response frame too short: {hex_data.hex()}")
# return False
# if hex_data[0] != 0x01 or hex_data[1] != 0x03 or hex_data[2] != 0x3C:
# rospy.logwarn(f"Battery response frame format error: {hex_data.hex()}")
# return False
# 更新电池数据
self.global_msg.header.stamp = rospy.Time.now()
self.global_msg.voltage = ((hex_data[3] << 8) | hex_data[4]) / 100.0
self.global_msg.percentage = ((hex_data[7] << 8) | hex_data[8])
unsigned_value = (hex_data[13] << 8) | hex_data[14]
# 转换为16位有符号整数
if unsigned_value & 0x8000:
signed_value = unsigned_value - 0x10000
else:
signed_value = unsigned_value # 正数直接使用
self.global_msg.current = signed_value / 100.0
self.global_msg.power_supply_status = 1 if self.global_msg.current > 0.5 else 0
self.global_msg.present = True
self.global_msg.temperature = (hex_data[61] << 8) | hex_data[62]
return True
except Exception as e:
rospy.loginfo(f"Error updating battery data: {e}")
return False
def update_alarm_data(self, hex_data):
"""更新全局消息中的报警数据"""
try:
# if len(hex_data) < 12:
# rospy.logwarn(f"Alarm response frame too short: {hex_data.hex()}")
# return False
# if hex_data[0] != 0x01 or hex_data[1] != 0x01 or hex_data[2] != 0x07:
# rospy.logwarn(f"Alarm response frame format error: {hex_data.hex()}")
# return False
# 更新报警数据
self.global_msg.header.stamp = rospy.Time.now()
alarm_code1 = hex_data[3]
self.global_msg.power_supply_health = alarm_code1
if ((hex_data[7] == 0) and (hex_data[8] == 0) and (hex_data[9] == 0)):
alarm_code_over_discharge_voltage = 0
else:
alarm_code_over_discharge_voltage = 1
if ((hex_data[6] == 0) and (hex_data[5] == 0) and (hex_data[4] < 16)):
alarm_code_over_charge_voltage = 0
else:
alarm_code_over_charge_voltage = 1
self.global_msg.power_supply_technology = (hex_data[4] & 0xF) | (alarm_code_over_charge_voltage << 4) | (alarm_code_over_discharge_voltage << 5)
return True
except Exception as e:
rospy.loginfo(f"Error updating alarm data: {e}")
return False
def receive_and_update(self):
"""接收数据并更新全局消息"""
data = self.ser.read_all()
if not data:
return False, "No data"
# 判断是否为电量响应
if data[0] == 0x01 and data[1] == 0x03 and data[2] == 0x3C:
success = self.update_battery_data(data)
return success, "Battery data updated"
# 判断是否为报警响应
elif data[0] == 0x01 and data[1] == 0x01 and data[2] == 0x07:
success = self.update_alarm_data(data)
return success, "Alarm data updated"
# 不符合任何类型
else:
rospy.loginfo(f"Unknown response frame: {data.hex()}")
return False, "Unknown frame"
def run(self):
while not rospy.is_shutdown():
try:
# 1. 发送电量指令并更新
self.ser.flushInput()
self.ser.write(self.battery_cmd)
rospy.logdebug(f"Sent battery command: {binascii.hexlify(self.battery_cmd).decode().upper()}")
time.sleep(0.19)
battery_success, battery_msg = self.receive_and_update()
if battery_success:
self.battery_pub.publish(self.global_msg)
# rospy.loginfo(f"Battery state updated: Voltage={self.global_msg.voltage:.2f}V, SOC={self.global_msg.percentage:.1f}%, Current={self.global_msg.current:.2f}A")
else:
rospy.loginfo(f"Battery update failed: {battery_msg}")
time.sleep(0.2)
# 2. 发送报警指令并更新
self.ser.flushInput()
self.ser.write(self.alarm_cmd)
rospy.logdebug(f"Sent alarm command: {binascii.hexlify(self.alarm_cmd).decode().upper()}")
time.sleep(0.08)
alarm_success, alarm_msg = self.receive_and_update()
if alarm_success:
self.battery_pub.publish(self.global_msg)
# rospy.loginfo(f"Alarm state updated: Health={self.global_msg.power_supply_health}")
else:
rospy.loginfo(f"Alarm update failed: {alarm_msg}")
except Exception as e:
rospy.logerr(f"Communication error: {e}")
self.rate.sleep()
if __name__ == '__main__':
try:
node = BMSDriverNode()
node.run()
except rospy.ROSInterruptException:
pass
finally:
if 'node' in locals() and hasattr(node, 'ser') and node.ser.is_open:
node.ser.close()
rospy.loginfo("BMS serial port closed")