__init__.py 31 KB

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