__init__.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  1. import rclpy
  2. from rclpy.node import Node
  3. from rclpy.time import Duration
  4. from nav_msgs.msg import OccupancyGrid
  5. from geometry_msgs.msg import Twist, PoseWithCovarianceStamped
  6. import cv2
  7. import json as js
  8. from .utils import Utils
  9. import time, random, math
  10. import asyncio
  11. import websockets
  12. """
  13. """
  14. class MapDataSub(Node):
  15. mapdata = OccupancyGrid()
  16. posdata = PoseWithCovarianceStamped()
  17. def __init__(self):
  18. super().__init__("mapdata_sub")
  19. self.mapping_sub = self.create_subscription(
  20. OccupancyGrid,
  21. '/map',
  22. self.mapping_cbk,
  23. 10
  24. )
  25. self.pos_sub = self.create_subscription(
  26. PoseWithCovarianceStamped,
  27. '/pose',
  28. self.pos_cbk,
  29. 10
  30. )
  31. def mapping_cbk(self, msg):
  32. self.mapdata = msg
  33. def pos_cbk(self, msg):
  34. self.posdata = msg
  35. # def quaternion_to_yaw(qx: float, qy: float, qz: float, qw: float) -> float:
  36. # """四元数转偏航角yaw(rad)"""
  37. # siny_cosp = 2 * (qw * qz + qx * qy)
  38. # cosy_cosp = qw**2 + qx**2 - qy**2 - qz**2
  39. # yaw = math.atan2(siny_cosp, cosy_cosp)
  40. # return yaw
  41. def quaternion_to_yaw(qx: float, qy: float, qz: float, qw: float) -> float:
  42. """
  43. ROS标准四元数(x,y,z,w)转绕Z轴偏航角yaw
  44. 返回弧度,范围 [-π, π]
  45. """
  46. # 修正后的标准计算公式
  47. siny_cosp = 2.0 * (qw * qz + qx * qy)
  48. cosy_cosp = 1.0 - 2.0 * (qy ** 2 + qz ** 2)
  49. yaw = math.atan2(siny_cosp, cosy_cosp)
  50. return math.degrees(yaw)
  51. def mapdata_sub(args=None):
  52. rclpy.init(args=args)
  53. node = MapDataSub()
  54. rclpy.spin_once(node)
  55. res1 = node.mapdata
  56. res2 = node.posdata
  57. node.destroy_node()
  58. rclpy.shutdown()
  59. res = {}
  60. if res1 is not None:
  61. res.update({
  62. "width": res1.info.width,
  63. "height": res1.info.height,
  64. "x": res1.info.origin.position.x,
  65. "y": res1.info.origin.position.y,
  66. "z": res1.info.origin.position.z,
  67. "resolution": res1.info.resolution,
  68. "data": str(res1.data)
  69. })
  70. if res2 is not None:
  71. res.update({
  72. "cur_x": res2.pose.pose.position.x,
  73. "cur_y": res2.pose.pose.position.y,
  74. "yaw": quaternion_to_yaw(res2.pose.pose.orientation.x,
  75. res2.pose.pose.orientation.y,
  76. res2.pose.pose.orientation.z,
  77. res2.pose.pose.orientation.w)})
  78. return res
  79. """
  80. """
  81. def map_edit(data=None):
  82. number = data.get("number")
  83. map_path = "/workspaces/srv/app/static/imgs/"
  84. pgm_path = "/workspaces/nav_ws/src/classic_nav_bringup/map/map.pgm"
  85. dir = ""
  86. default_map = r"/workspaces/srv/app/static/js/default_map.json"
  87. try:
  88. with open(default_map, "r+", encoding="utf-8") as f:
  89. n = f.read()
  90. n = "" if n == "" else js.loads(n)
  91. if number == n.get("number"):
  92. dir = pgm_path
  93. f.close()
  94. except FileNotFoundError:
  95. with open(default_map, "w+", encoding="utf-8") as f:
  96. f.write("")
  97. f.close()
  98. # img = cv2.imread("/workspaces/nav_ws/src/classic_nav_bringup/map/map.pgm", cv2.IMREAD_UNCHANGED)
  99. if number == None or number == "":
  100. number = ""
  101. dir = pgm_path
  102. elif dir == "":
  103. dir = f"{map_path}{number}/map.pgm"
  104. srv_path = f"{map_path}{number}/map.pgm"
  105. img = cv2.imread(dir, cv2.IMREAD_UNCHANGED)
  106. if img is None:
  107. print("no pgm file")
  108. return "unsaved"
  109. if data is not None:
  110. for obs in data.get("obs"):
  111. op = obs[4]
  112. match op:
  113. case 4:
  114. cv2.rectangle(img, (obs[0], obs[1]), (obs[2], obs[3]), (0, 0, 0), -1, 8)
  115. case 5:
  116. cv2.line(img, (obs[0], obs[1]), (obs[2], obs[3]), (0, 0, 0), 3)
  117. for erase in data.get("erase"):
  118. op = erase[4]
  119. match op:
  120. case 4:
  121. cv2.rectangle(img, (erase[0], erase[1]), (erase[2], erase[3]), (255, 255, 255), -1, 8)
  122. case 5:
  123. cv2.line(img, (obs[0], obs[1]), (obs[2], obs[3]), (0, 0, 0), 3)
  124. # cv2.imwrite("/workspaces/nav_ws/src/classic_nav_bringup/map/map.pgm", img)
  125. cv2.imwrite(dir, img)
  126. cv2.imwrite(srv_path, img)
  127. # subprocess.run(["curl", "-X", "POST", "-F" f"pgm=@{dir}/map.pgm", "-F", f"yaml=@{dir}/map.yaml", f"http://localhost:5000/upload_map"], shell=False)
  128. return number
  129. def map_edit2(data=None):
  130. number = data.get("number")
  131. map_path = "/workspaces/srv/app/static/imgs/"
  132. # download: curl -o map.pgm http://localhost:5555/api/maps/Secure_911/pgm/map.pgm
  133. # subprocess.run(["curl", "-o", "map.pgm", f"http://localhost:5555/api/maps/{number}/pgm/map.pgm"], shell=False)
  134. # subprocess.run(["curl", "-o", "map.yaml", f"http://localhost:5555/api/maps/{number}/pgm/map.yaml"], shell=False)
  135. # draw
  136. # img = cv2.imread(f"{map_path}map.pgm", cv2.IMREAD_UNCHANGED)
  137. img = cv2.imread(f"{map_path}map.pgm", cv2.IMREAD_UNCHANGED)
  138. if img is None:
  139. print("no pgm file")
  140. return "unsaved"
  141. if data is not None:
  142. for obs in data.get("obs"):
  143. if len(obs) == 0:
  144. continue
  145. op = obs[4]
  146. match op:
  147. case 4:
  148. cv2.rectangle(img, (obs[0], obs[1]), (obs[2], obs[3]), (0, 0, 0), -1, 8)
  149. case 5:
  150. cv2.line(img, (obs[0], obs[1]), (obs[2], obs[3]), (0, 0, 0), 3)
  151. case 6:
  152. cv2.rectangle(img, (erase[0], erase[1]), (erase[2], erase[3]), (255, 255, 255), -1, 8)
  153. case 7:
  154. cv2.line(img, (obs[0], obs[1]), (obs[2], obs[3]), (255, 255, 255), 3)
  155. for erase in data.get("erase"):
  156. if len(erase) == 0:
  157. continue
  158. op = erase[4]
  159. match op:
  160. case 4:
  161. cv2.rectangle(img, (erase[0], erase[1]), (erase[2], erase[3]), (255, 255, 255), -1, 8)
  162. case 5:
  163. cv2.line(img, (obs[0], obs[1]), (obs[2], obs[3]), (255, 255, 255), 3)
  164. cv2.imwrite(f"{map_path}map.pgm", img)
  165. cv2.imwrite(f"{map_path}{number}/map.pgm", img)
  166. # upload: curl -X POST -F "pgm=@/path/to/your/map.pgm" -F "yaml=@/path/to/your/map.yaml" http://localhost:5000/upload_map
  167. ret = subprocess.run(["curl", "-X", "POST", "-F", f"pgm=@{map_path}/map.pgm", "-F", f"yaml=@/{map_path}/map.yaml", "http://localhost:5000/upload_map"], shell=False)
  168. print(ret)
  169. subprocess.run(["convert", f"{map_path}{number}/map.pgm", f"{map_path}{number}/map.png"], shell=False)
  170. subprocess.run(["python3", "/workspacs/ws/client/map_save.py", "--map", f"{number}", "--dir", f"{map_path}{number}"], shell=False)
  171. return number
  172. # import serial
  173. # def mot_ctrl():
  174. # # ser = serial.Serial("/dev/ttyUSB1", 1_000_000, timeout=-1)
  175. # # if ser.isOpen():
  176. # # ser.write(bytes.fromhex(data.encode("utf-8").hex()))
  177. # # ser.close()
  178. # # return ""
  179. # ser = serial.Serial("/dev/ttyUSB1", 1_000_000, timeout=-1)
  180. # ret = ""
  181. # if ser.isOpen():
  182. # ser.write(bytes.fromhex(data.encode("utf-8").hex()))
  183. # ret = ser.readall()
  184. # ser.close()
  185. # return ret
  186. """
  187. """
  188. def station_edit(data=None):
  189. ret = ""
  190. if data is not None:
  191. u = Utils()
  192. op = data.get("op")
  193. number = data.get("number")
  194. if number == None or number == "":
  195. number = f"map{time.time()*1000:.0f}{random.randint(1000, 9999)}"
  196. dir = f"/workspaces/srv/app/static/imgs/{number}"
  197. if op == u.UPD and not os.path.exists(dir):
  198. os.mkdir(dir)
  199. subprocess.run(["bash", "/workspaces/srv/sh/9manage_map.sh", str(u.UPD), str(number)], shell=False)
  200. file_path = f"{dir}/stations.json"
  201. match op:
  202. case u.GET:
  203. try:
  204. with open(file_path, "r+", encoding="utf-8") as f:
  205. ret = f.read()
  206. ret = "" if ret == "" else js.loads(ret)
  207. f.close()
  208. except FileNotFoundError:
  209. with open(file_path, "w+", encoding="utf-8") as f:
  210. f.write("")
  211. f.close()
  212. case u.UPD:
  213. with open(file_path, "w+", encoding="utf-8") as f:
  214. js.dump(data.get("stations"), f, ensure_ascii=False)
  215. ret = "Update"
  216. f.close()
  217. subprocess.run(["python3", "/workspacs/ws/client/map_save.py", "--map", f"{number}", "--dir", f"{dir}"], shell=False)
  218. case u.CLS:
  219. with open(file_path, "w+", encoding="utf-8") as f:
  220. f.write("")
  221. ret = "Clear"
  222. f.close()
  223. subprocess.run(["python3", "/workspacs/ws/client/map_save.py", "--map", f"{number}", "--dir", f"{dir}"], shell=False)
  224. return {"ret": ret, "number": number}
  225. def schedule(data=None):
  226. ret = ""
  227. if data is not None:
  228. u = Utils()
  229. op = data.get("op")
  230. number = data.get("number")
  231. file_path = f"/workspaces/srv/app/static/imgs/{number}/sechudle.json"
  232. match op:
  233. case u.GET:
  234. try:
  235. with open(file_path, "r", encoding="utf-8") as f:
  236. ret = f.read()
  237. ret = "" if ret == "" else js.loads(ret)
  238. f.close()
  239. except FileNotFoundError:
  240. with open(file_path, "w+", encoding="utf-8") as f:
  241. f.write("")
  242. f.close()
  243. case u.UPD:
  244. with open(file_path, "w+", encoding="utf-8") as f:
  245. js.dump(data.get("schedule"), f, ensure_ascii=False)
  246. ret = "Update"
  247. f.close()
  248. case u.CLS:
  249. with open(file_path, "w+", encoding="utf-8") as f:
  250. f.write("")
  251. ret = "Clear"
  252. f.close()
  253. case u.EXC:
  254. try:
  255. with open(file_path, "r", encoding="utf-8") as f:
  256. payloads = f.read()
  257. f.close()
  258. except FileNotFoundError:
  259. ret = "No schedule"
  260. return ret
  261. """
  262. """
  263. def upgrade_info(data=None):
  264. file_path = f"/workspaces/srv/app/static/templates/{data.get('info')}"
  265. ret = ""
  266. try:
  267. with open(file_path, "r", encoding="utf-8") as f:
  268. ret = f.read()
  269. f.close()
  270. except FileNotFoundError:
  271. with open(file_path, "w+", encoding="utf-8") as f:
  272. f.write("0")
  273. f.close()
  274. return ret
  275. """
  276. """
  277. import os, subprocess
  278. import platform
  279. from datetime import datetime as dt
  280. def get_file_create_time(file_path: str) -> str:
  281. """兼容多系统获取文件创建时间,返回格式化字符串"""
  282. stat = os.stat(file_path)
  283. sys_name = platform.system()
  284. if sys_name == "Windows":
  285. create_timestamp = stat.st_ctime
  286. elif sys_name == "Darwin": # macOS
  287. create_timestamp = stat.st_birthtime
  288. else: # Linux 无原生创建时间,改用修改时间替代
  289. create_timestamp = stat.st_mtime
  290. # 格式化时间
  291. create_time = dt.fromtimestamp(create_timestamp).strftime("%Y-%m-%d %H:%M:%S")
  292. return create_time
  293. def scan_log_files(root_dir: str):
  294. """递归扫描所有.log文件,组装数据列表"""
  295. result_list = []
  296. # 遍历目录树
  297. for dirpath, _, filenames in os.walk(root_dir):
  298. for filename in filenames:
  299. if filename.lower().endswith(".log"):
  300. file_full_path = os.path.join(dirpath, filename)
  301. # 相对路径:目录名/文件名
  302. rel_path = os.path.relpath(file_full_path, root_dir).replace(os.sep, "/")
  303. # content = "..."
  304. # file_disk_size = os.path.getsize(file_full_path)
  305. # 读取文件内容(捕获编码异常)
  306. try:
  307. with open(file_full_path, "r", encoding="utf-8") as f:
  308. content = f.read(102_400)
  309. except UnicodeDecodeError:
  310. with open(file_full_path, "r", encoding="gbk", errors="ignore") as f:
  311. content = f.read(102_400)
  312. # 获取创建时间
  313. create_time = get_file_create_time(file_full_path)
  314. # 组装单条数据
  315. file_info = {
  316. "file_path": rel_path, # 目录名称/文件名称
  317. "file_content": content, # 文件内容
  318. "file_create_time": create_time # 文件创建时间
  319. }
  320. result_list.append(file_info)
  321. return result_list
  322. def logger(data=None):
  323. op = data.get("op")
  324. u = Utils()
  325. file_path = r"/workspaces/log/"
  326. match op:
  327. case u.GET:
  328. log_data = scan_log_files(file_path)
  329. return log_data
  330. json_str = js.dumps(log_data, ensure_ascii=False, indent=2)
  331. return json_str
  332. case u.CLS:
  333. subprocess.run(["bash", "/workspaces/srv/sh/8clear_log.sh"], shell=False)
  334. return "done"
  335. case _:
  336. return ""
  337. """
  338. """
  339. import socket
  340. import psutil
  341. from pywifi import PyWiFi, const
  342. def run_cmd(cmd: str) -> str:
  343. """执行shell命令,返回输出文本"""
  344. try:
  345. res = subprocess.check_output(cmd, shell=True, text=True, stderr=subprocess.STDOUT)
  346. return res.strip()
  347. except subprocess.CalledProcessError:
  348. return ""
  349. def get_hostname() -> str:
  350. """主机名"""
  351. return socket.gethostname()
  352. def get_cpu_info() -> dict:
  353. """CPU信息:核心数、使用率、温度"""
  354. cpu_count = psutil.cpu_count(logical=True)
  355. cpu_phys_count = psutil.cpu_count(logical=False) or cpu_count
  356. cpu_percent = psutil.cpu_percent(interval=0.5)
  357. cpu_freq = psutil.cpu_freq()
  358. # CPU温度
  359. temp_text = run_cmd("sensors")
  360. cpu_temp = []
  361. for line in temp_text.splitlines():
  362. if "Core" in line and "+" in line:
  363. cpu_temp.append(line.strip())
  364. return {
  365. "physical_core": cpu_phys_count,
  366. "logical_core": cpu_count,
  367. "usage_percent": cpu_percent,
  368. "current_freq_mhz": round(cpu_freq.current, 2) if cpu_freq else None,
  369. "max_freq_mhz": round(cpu_freq.max, 2) if cpu_freq else None,
  370. "temperature": cpu_temp
  371. }
  372. def get_memory_info() -> dict:
  373. """内存信息"""
  374. mem = psutil.virtual_memory()
  375. swap = psutil.swap_memory()
  376. def mb(val): return round(val / 1024 / 1024, 2)
  377. return {
  378. "total_mb": mb(mem.total),
  379. "used_mb": mb(mem.used),
  380. "free_mb": mb(mem.free),
  381. "available_mb": mb(mem.available),
  382. "usage_percent": mem.percent,
  383. "swap_total_mb": mb(swap.total),
  384. "swap_used_mb": mb(swap.used)
  385. }
  386. def get_disk_info() -> list:
  387. """磁盘分区挂载信息"""
  388. disks = []
  389. for part in psutil.disk_partitions(all=False):
  390. try:
  391. usage = psutil.disk_usage(part.mountpoint)
  392. def gb(val): return round(val / 1024 / 1024 / 1024, 2)
  393. disks.append({
  394. "device": part.device,
  395. "mount_point": part.mountpoint,
  396. "fstype": part.fstype,
  397. "total_gb": gb(usage.total),
  398. "used_gb": gb(usage.used),
  399. "free_gb": gb(usage.free),
  400. "usage_percent": usage.percent
  401. })
  402. except PermissionError:
  403. continue
  404. return disks
  405. def get_gpu_info() -> list:
  406. """GPU信息(nvidia显卡,无nvidia-smi返回空)"""
  407. gpu_list = []
  408. gpu_raw = run_cmd("nvidia-smi --query-gpu=name,memory.total,memory.used,temperature.gpu --format=csv,noheader,nounits")
  409. if not gpu_raw:
  410. return gpu_list
  411. for line in gpu_raw.splitlines():
  412. parts = [p.strip() for p in line.split(",")]
  413. if len(parts) == 4:
  414. gpu_list.append({
  415. "name": parts[0],
  416. "total_memory_mb": parts[1],
  417. "used_memory_mb": parts[2],
  418. "temp_c": parts[3]
  419. })
  420. return gpu_list
  421. def get_network_info() -> list:
  422. """网卡:MAC、IP、WIFI名称、信号强度"""
  423. net_info = []
  424. wifi = PyWiFi()
  425. interfaces = wifi.interfaces()
  426. # 获取WIFI当前连接信息
  427. wifi_signal_map = {}
  428. for iface in interfaces:
  429. if iface.status() == const.IFACE_CONNECTED:
  430. profile = iface.network_profiles()[0] if iface.network_profiles() else None
  431. sig = iface.signal()
  432. ssid = profile.ssid if profile else ""
  433. wifi_signal_map[iface.name()] = {
  434. "ssid": ssid,
  435. "signal_dbm": sig
  436. }
  437. # 遍历网卡
  438. for name, addrs in psutil.net_if_addrs().items():
  439. mac = ""
  440. ipv4 = ""
  441. for addr in addrs:
  442. if addr.family == psutil.AF_LINK:
  443. mac = addr.address
  444. elif addr.family == socket.AF_INET:
  445. ipv4 = addr.address
  446. if not mac:
  447. continue
  448. wifi_data = wifi_signal_map.get(name, {})
  449. net_info.append({
  450. "nic_name": name,
  451. "mac_address": mac,
  452. "ipv4": ipv4,
  453. "wifi_ssid": wifi_data.get("ssid", ""),
  454. "wifi_signal_dbm": wifi_data.get("signal_dbm", None)
  455. })
  456. return net_info
  457. def get_usb_devices() -> list:
  458. """挂载USB设备"""
  459. usb_list = []
  460. usb_raw = run_cmd("lsusb")
  461. for line in usb_raw.splitlines():
  462. if line.strip():
  463. usb_list.append(line.strip())
  464. return usb_list
  465. def collect_all_info() -> dict:
  466. data = {
  467. "host_name": get_hostname(),
  468. "cpu": get_cpu_info(),
  469. "memory": get_memory_info(),
  470. "disk": get_disk_info(),
  471. "gpu": get_gpu_info(),
  472. "usb_devices": get_usb_devices()
  473. }
  474. # "network": get_network_info(),
  475. return data
  476. from rclpy.qos import QoSProfile, QoSReliabilityPolicy
  477. from ros2cli.node.strategy import NodeStrategy
  478. def get_all_nodes() -> list:
  479. """获取当前所有运行节点名称"""
  480. with NodeStrategy([]) as node:
  481. node_names = node.get_node_names_and_namespaces()
  482. nodes = [f"{ns}/{name}" if ns != "/" else f"/{name}" for name, ns in node_names]
  483. return nodes
  484. class ROS2TopicMonitor(Node):
  485. def __init__(self):
  486. super().__init__("ros2_topic_monitor")
  487. self.topic_subs = {} # 存储话题订阅器
  488. self.topic_data_cache = {} # 缓存最新话题消息数据
  489. def get_all_nodes_topics(self):
  490. """获取当前所有运行节点、所有话题+消息类型"""
  491. # 获取全部节点
  492. node_names = self.get_node_names()
  493. node_list = []
  494. for name in node_names:
  495. node_list.append({"node_name": name})
  496. # 获取所有话题及对应消息类型
  497. topic_info_list = []
  498. all_topics = self.get_topic_names_and_types()
  499. for topic_name, type_list in all_topics:
  500. topic_info_list.append({
  501. "topic_name": topic_name,
  502. "msg_types": type_list
  503. })
  504. return {
  505. "running_nodes": node_list,
  506. "all_topics": topic_info_list
  507. }
  508. def subscribe_topic(self, topic_name, msg_type_str):
  509. """动态订阅指定话题,解析消息类型"""
  510. if topic_name in self.topic_subs:
  511. return True
  512. try:
  513. # 拆分消息类型:如 std_msgs/msg/String
  514. pkg, msg_module, msg_cls = msg_type_str.split("/")
  515. import importlib
  516. msg_module_obj = importlib.import_module(f"{pkg}.{msg_module}")
  517. msg_class = getattr(msg_module_obj, msg_cls)
  518. except Exception as e:
  519. print(f"无法加载消息类型 {msg_type_str}: {str(e)}")
  520. return False
  521. # QoS配置,兼容大部分话题
  522. qos = QoSProfile(reliability=QoSReliabilityPolicy.RELIABLE, depth=10)
  523. def callback(msg):
  524. """话题消息回调,缓存最新数据"""
  525. self.topic_data_cache[topic_name] = self.msg_to_dict(msg)
  526. sub = self.create_subscription(msg_class, topic_name, callback, qos)
  527. self.topic_subs[topic_name] = sub
  528. print(f"已订阅话题: {topic_name}")
  529. return True
  530. def msg_to_dict(self, msg):
  531. """ROS消息对象转字典(递归解析嵌套消息)"""
  532. if hasattr(msg, "get_fields_and_field_types"):
  533. data = {}
  534. fields = msg.get_fields_and_field_types()
  535. for field_name, _ in fields.items():
  536. val = getattr(msg, field_name)
  537. # 递归处理嵌套消息
  538. if hasattr(val, "get_fields_and_field_types"):
  539. data[field_name] = self.msg_to_dict(val)
  540. elif isinstance(val, list):
  541. arr = []
  542. for item in val:
  543. if hasattr(item, "get_fields_and_field_types"):
  544. arr.append(self.msg_to_dict(item))
  545. else:
  546. arr.append(item)
  547. data[field_name] = arr
  548. else:
  549. data[field_name] = val
  550. return data
  551. return msg
  552. def get_topic_latest_data(self, topic_name):
  553. """获取指定话题最新缓存数据"""
  554. return self.topic_data_cache.get(topic_name, "暂无收到任何消息")
  555. def get_node_pub_sub_info(ros_node, target_node):
  556. """查询单个节点的发布、订阅话题"""
  557. # 拆分节点名与命名空间
  558. if "/" in target_node:
  559. parts = target_node.rsplit("/", 1)
  560. node_ns = parts[0] if parts[0] != "" else "/"
  561. node_name = parts[1]
  562. else:
  563. node_ns = "/"
  564. node_name = target_node
  565. # 传入 node_name + node_namespace 两个参数
  566. pub_topics = ros_node.get_publisher_names_and_types_by_node(node_name, node_ns)
  567. sub_topics = ros_node.get_subscriber_names_and_types_by_node(node_name, node_ns)
  568. return {
  569. "node_name": target_node,
  570. "publish_topics": [{"topic": t, "types": ty} for t, ty in pub_topics],
  571. "subscribe_topics": [{"topic": t, "types": ty} for t, ty in sub_topics]
  572. }
  573. def monitor(data=None):
  574. info = []
  575. all_nodes_topics = None
  576. sys_info = data.get("sys_info")
  577. ros2_info = data.get("ros2_info")
  578. ros2_node = data.get("ros2_node")
  579. ros2_topic = data.get("ros2_topic")
  580. # print(ros2_info, ros2_node, ros2_topic)
  581. if sys_info:
  582. sys_data = collect_all_info()
  583. info.append({"sys": sys_data})
  584. if ros2_info:
  585. result = subprocess.run("ros2 node list", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8")
  586. out_text = result.stdout
  587. lines = out_text.splitlines()
  588. info.append(lines)
  589. # info.append({"nodes": lines})
  590. # result = subprocess.run("ros2 topic list", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8")
  591. # out_text = result.stdout
  592. # lines = out_text.splitlines()
  593. # info.append({"topics": lines})
  594. # result = subprocess.run("ros2 service list", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8")
  595. # out_text = result.stdout
  596. # lines = out_text.splitlines()
  597. # info.append({"service": lines})
  598. if ros2_topic != None:
  599. result = subprocess.run(f"ros2 topic echo {ros2_topic}", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8")
  600. out_text = result.stdout
  601. # lines = out_text.splitlines()
  602. info.append({"topic": ros2_topic, "ctx": out_text})
  603. return info
  604. # if ros2_topic != "" != None and len(ros2_node) > 0:
  605. # return ""
  606. # rclpy.init()
  607. # monitor = ROS2TopicMonitor()
  608. # executor = rclpy.executors.MultiThreadedExecutor()
  609. # executor.add_node(monitor)
  610. # all_topic_data = monitor.get_all_nodes_topics()["all_topics"]
  611. # monitor.destroy_node()
  612. # rclpy.shutdown()
  613. # return all_topic_data
  614. # print(f"topics: {all_topic_data}")
  615. # match_topic = None
  616. # for t in all_topic_data:
  617. # if t["topic_name"] == ros2_topic:
  618. # match_topic = t
  619. # break
  620. # if not match_topic:
  621. # print(f"不存在话题 {ros2_topic}")
  622. # return "not exist"
  623. # # 订阅该话题所有消息类型
  624. # for msg_type in match_topic["msg_types"]:
  625. # monitor.subscribe_topic(ros2_topic, msg_type)
  626. # executor.spin_once(timeout_sec=0.1)
  627. # latest = monitor.get_topic_latest_data(ros2_topic)
  628. # # data_json = js.dumps({"topic": ros2_topic, "latest_data": latest}, ensure_ascii=False, indent=2)
  629. # monitor.destroy_node()
  630. # rclpy.shutdown()
  631. # return latest
  632. """
  633. """
  634. def get_files(target_dir, prefix=(), suffix=(), fd=2):
  635. """
  636. 读取指定目录下以bk开头,后缀为pgm、yaml、pcd的文件
  637. :param target_dir: 目标文件夹路径
  638. :return: 匹配的文件名列表
  639. """
  640. # 定义允许的后缀
  641. # suffix_list = (".pgm", ".yaml", ".pcd")
  642. match_files = []
  643. # 遍历目录下所有文件
  644. for filename in os.listdir(target_dir):
  645. # 拼接完整路径,判断是否为文件(排除文件夹)
  646. full_path = os.path.join(target_dir, filename)
  647. if (len(prefix) == 0 or filename.startswith(prefix)) and \
  648. (len(suffix) == 0 or filename.endswith(suffix)):
  649. if fd & 1 and os.path.isfile(full_path):
  650. match_files.append(filename[:filename.rfind(".")])
  651. if fd & 2 and os.path.isdir(full_path):
  652. match_files.append(filename)
  653. return match_files
  654. """
  655. """
  656. def map_manager(data=None):
  657. op = data.get("op")
  658. u = Utils()
  659. sh = r"/workspaces/srv/sh/9manage_map.sh"
  660. srv_dir = r"/workspaces/srv/app/static/imgs/"
  661. default_map = r"/workspaces/srv/app/static/js/default_map.json"
  662. hardware = r"/workspaces/srv/app/static/js/hardware.json"
  663. prefix = data.get("number")
  664. match op:
  665. case u.GET:
  666. # get all map infomation
  667. return get_files(srv_dir, prefix=("map"))
  668. case u.UPD:
  669. pass
  670. return "done"
  671. case u.CLS:
  672. # delete the map
  673. try:
  674. with open(default_map, "r+", encoding="utf-8") as f:
  675. r = f.read()
  676. r = "" if r == "" else js.loads(r)
  677. if r == prefix:
  678. f.write(r'{"number": ""}')
  679. f.close()
  680. with open(hardware, "r+", encoding="utf-8") as f:
  681. hardware_info = js.loads(f.read())
  682. subprocess.run(["python3", "/workspaces/ws/client/map_delete.py", \
  683. "--map", f"{prefix}", "--device", hardware_info.get("sn"), \
  684. "--secret", hardware_info.get("key")], shell=False)
  685. except FileNotFoundError:
  686. with open(default_map, "w+", encoding="utf-8") as f:
  687. f.write("")
  688. f.close()
  689. subprocess.run(["bash", sh, str(u.CLS), prefix], shell=False)
  690. return "done"
  691. case u.EXC:
  692. # set up default map
  693. # with open(default_map, "w+", encoding="utf-8") as f:
  694. # js.dump({"number": prefix}, f, ensure_ascii=False)
  695. # f.close()
  696. subprocess.run(["bash", sh, str(u.EXC), prefix], shell=False)
  697. return "done"
  698. case 5:
  699. ret = ""
  700. try:
  701. with open(default_map, "r+", encoding="utf-8") as f:
  702. ret = f.read()
  703. ret = "" if ret == "" else js.loads(ret)
  704. f.close()
  705. except FileNotFoundError:
  706. with open(default_map, "w+", encoding="utf-8") as f:
  707. f.write("")
  708. f.close()
  709. return ret
  710. return "none"
  711. """
  712. """
  713. def set_manager(data=None):
  714. u = Utils()
  715. op = data.get("op")
  716. sh = r"/workspaces/srv/sh/10manage_setting.sh"
  717. srv_dir = r"/workspaces/srv/app/static/js/"
  718. default_setting = r"/workspaces/srv/app/static/js/default_setting.json"
  719. prefix = data.get("number")
  720. match op:
  721. case u.GET:
  722. if prefix != None:
  723. return get_files(f"{srv_dir}{prefix}")
  724. else:
  725. # get all projects
  726. return get_files(srv_dir, prefix=("setting"))
  727. case u.UPD:
  728. file = data.get("file")
  729. if prefix != None and file != None:
  730. with open(f"{srv_dir}{prefix}/{file}", "w+", encoding="utf-8") as f:
  731. js.dump(data.get("setting"), f, ensure_ascii=False)
  732. ret = "Update"
  733. f.close()
  734. else:
  735. ret = "configuration number or file is none"
  736. case u.CLS:
  737. # delete the project
  738. try:
  739. with open(default_setting, "r+", encoding="utf-8") as f:
  740. r = f.read()
  741. r = "" if r == "" else js.loads(r)
  742. if r == prefix:
  743. f.write(r'{"number": ""}')
  744. f.close()
  745. except FileNotFoundError:
  746. with open(default_setting, "w+", encoding="utf-8") as f:
  747. f.write("")
  748. f.close()
  749. subprocess.run(["bash", sh, str(u.CLS), prefix], shell=False)
  750. return "done"
  751. case u.EXC:
  752. # set up default project
  753. subprocess.run(["bash", sh, str(u.EXC), prefix], shell=False)
  754. return "done"
  755. case 5:
  756. ret = ""
  757. try:
  758. with open(default_setting, "r+", encoding="utf-8") as f:
  759. ret = f.read()
  760. ret = "" if ret == "" else js.loads(ret)
  761. f.close()
  762. except FileNotFoundError:
  763. with open(default_setting, "w+", encoding="utf-8") as f:
  764. f.write("")
  765. f.close()
  766. return ret
  767. return "none"
  768. """
  769. """
  770. def vision(data=None):
  771. op = data.get("op")
  772. match op:
  773. case 5:
  774. # yolo
  775. subprocess.run(["bash", "/workspaces/srv/sh/11run_yolo_pose.sh"], shell=False)
  776. return "done"
  777. case 6:
  778. pass
  779. # mapping
  780. subprocess.run(["bash", "/workspaces/srv/sh/12start_rtab.sh"], shell=False)
  781. return "done"
  782. return "none"
  783. """
  784. """
  785. def recorder(data=None):
  786. op = data.get("op")
  787. u = Utils()
  788. number = data.get("number")
  789. srv_dir = r"/workspaces/srv/app/static/rec/"
  790. match op:
  791. case u.GET:
  792. return get_files(srv_dir, prefix=("nav_bag_"))
  793. case u.CLS:
  794. subprocess.run(["bash", "/workspaces/srv/sh/13recorder.sh", str(u.CLS), str(number)], shell=False)
  795. return "done"
  796. case 4:
  797. if number == None:
  798. subprocess.run(["bash", "/workspaces/srv/sh/13recorder.sh", "4"], shell=False)
  799. else:
  800. subprocess.run(["bash", "/workspaces/srv/sh/13recorder.sh", "4", str(number)], shell=False)
  801. return "done"
  802. case 5:
  803. subprocess.run(["bash", "/workspaces/srv/sh/13recorder.sh", "5"], shell=False)
  804. return "done"
  805. case 6:
  806. if number != None:
  807. with open(f"{srv_dir}{number}/schedule.json", "w+", encoding="utf-8") as f:
  808. js.dump(data.get("schedule"), f, ensure_ascii=False)
  809. f.close()
  810. return "done"
  811. return "none"
  812. async def websocket_client(payload=""):
  813. try:
  814. async with websockets.connect("http://127.0.0.1:9001") as websocket:
  815. # 向服务器发送消息
  816. await websocket.send(payload)
  817. # 接收来自服务器的消息
  818. resp = await websocket.recv()
  819. except Exception as e:
  820. print(f"{e}")