__init__.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  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. file_path = r"/workspaces/srv/app/static/rec"
  327. hardware_path = r"/workspaces/srv/app/static/js/hardware.json"
  328. match op:
  329. case u.GET:
  330. log_data = scan_log_files(file_path)
  331. return log_data
  332. json_str = js.dumps(log_data, ensure_ascii=False, indent=2)
  333. return json_str
  334. case u.UPD:
  335. number = data.get("number")
  336. log = data.get("log")
  337. # UPLOAD
  338. try:
  339. with open(hardware_path, "r+", encoding="utf-8") as f:
  340. hardware_info = js.loads(f.read())
  341. f.close()
  342. sn, key = hardware_info.get("sn"), hardware_info.get("key")
  343. subprocess.run(["python3", "/workspaces/ws/client/nav_recoder_client", "--action",\
  344. "upload", "--device", f"{sn}", "--secret", f"{key}", "--map", f"{log.get()}",\
  345. "--batch-id", f"{log.get()}", "--sites", f"{log.get()}", "--path", f"{log.get()}",\
  346. "--log", "", "--base"])
  347. log["tag"] = "upload"
  348. except:
  349. log["tag"] = ""
  350. with open(f"{file_path}/{number}.json", "w+", encoding="utf-8") as f:
  351. js.dumps(log, f, ensure_ascii=False)
  352. f.close()
  353. case u.CLS:
  354. subprocess.run(["bash", "/workspaces/srv/sh/8clear_log.sh", str(data.get("number"))], shell=False)
  355. return "done"
  356. case _:
  357. return ""
  358. """
  359. """
  360. import socket
  361. import psutil
  362. from pywifi import PyWiFi, const
  363. def run_cmd(cmd: str) -> str:
  364. """执行shell命令,返回输出文本"""
  365. try:
  366. res = subprocess.check_output(cmd, shell=True, text=True, stderr=subprocess.STDOUT)
  367. return res.strip()
  368. except subprocess.CalledProcessError:
  369. return ""
  370. def get_hostname() -> str:
  371. """主机名"""
  372. return socket.gethostname()
  373. def get_cpu_info() -> dict:
  374. """CPU信息:核心数、使用率、温度"""
  375. cpu_count = psutil.cpu_count(logical=True)
  376. cpu_phys_count = psutil.cpu_count(logical=False) or cpu_count
  377. cpu_percent = psutil.cpu_percent(interval=0.5)
  378. cpu_freq = psutil.cpu_freq()
  379. # CPU温度
  380. temp_text = run_cmd("sensors")
  381. cpu_temp = []
  382. for line in temp_text.splitlines():
  383. if "Core" in line and "+" in line:
  384. cpu_temp.append(line.strip())
  385. return {
  386. "physical_core": cpu_phys_count,
  387. "logical_core": cpu_count,
  388. "usage_percent": cpu_percent,
  389. "current_freq_mhz": round(cpu_freq.current, 2) if cpu_freq else None,
  390. "max_freq_mhz": round(cpu_freq.max, 2) if cpu_freq else None,
  391. "temperature": cpu_temp
  392. }
  393. def get_memory_info() -> dict:
  394. """内存信息"""
  395. mem = psutil.virtual_memory()
  396. swap = psutil.swap_memory()
  397. def mb(val): return round(val / 1024 / 1024, 2)
  398. return {
  399. "total_mb": mb(mem.total),
  400. "used_mb": mb(mem.used),
  401. "free_mb": mb(mem.free),
  402. "available_mb": mb(mem.available),
  403. "usage_percent": mem.percent,
  404. "swap_total_mb": mb(swap.total),
  405. "swap_used_mb": mb(swap.used)
  406. }
  407. def get_disk_info() -> list:
  408. """磁盘分区挂载信息"""
  409. disks = []
  410. for part in psutil.disk_partitions(all=False):
  411. try:
  412. usage = psutil.disk_usage(part.mountpoint)
  413. def gb(val): return round(val / 1024 / 1024 / 1024, 2)
  414. disks.append({
  415. "device": part.device,
  416. "mount_point": part.mountpoint,
  417. "fstype": part.fstype,
  418. "total_gb": gb(usage.total),
  419. "used_gb": gb(usage.used),
  420. "free_gb": gb(usage.free),
  421. "usage_percent": usage.percent
  422. })
  423. except PermissionError:
  424. continue
  425. return disks
  426. def get_gpu_info() -> list:
  427. """GPU信息(nvidia显卡,无nvidia-smi返回空)"""
  428. gpu_list = []
  429. gpu_raw = run_cmd("nvidia-smi --query-gpu=name,memory.total,memory.used,temperature.gpu --format=csv,noheader,nounits")
  430. if not gpu_raw:
  431. return gpu_list
  432. for line in gpu_raw.splitlines():
  433. parts = [p.strip() for p in line.split(",")]
  434. if len(parts) == 4:
  435. gpu_list.append({
  436. "name": parts[0],
  437. "total_memory_mb": parts[1],
  438. "used_memory_mb": parts[2],
  439. "temp_c": parts[3]
  440. })
  441. return gpu_list
  442. def get_network_info() -> list:
  443. """网卡:MAC、IP、WIFI名称、信号强度"""
  444. net_info = []
  445. wifi = PyWiFi()
  446. interfaces = wifi.interfaces()
  447. # 获取WIFI当前连接信息
  448. wifi_signal_map = {}
  449. for iface in interfaces:
  450. if iface.status() == const.IFACE_CONNECTED:
  451. profile = iface.network_profiles()[0] if iface.network_profiles() else None
  452. sig = iface.signal()
  453. ssid = profile.ssid if profile else ""
  454. wifi_signal_map[iface.name()] = {
  455. "ssid": ssid,
  456. "signal_dbm": sig
  457. }
  458. # 遍历网卡
  459. for name, addrs in psutil.net_if_addrs().items():
  460. mac = ""
  461. ipv4 = ""
  462. for addr in addrs:
  463. if addr.family == psutil.AF_LINK:
  464. mac = addr.address
  465. elif addr.family == socket.AF_INET:
  466. ipv4 = addr.address
  467. if not mac:
  468. continue
  469. wifi_data = wifi_signal_map.get(name, {})
  470. net_info.append({
  471. "nic_name": name,
  472. "mac_address": mac,
  473. "ipv4": ipv4,
  474. "wifi_ssid": wifi_data.get("ssid", ""),
  475. "wifi_signal_dbm": wifi_data.get("signal_dbm", None)
  476. })
  477. return net_info
  478. def get_usb_devices() -> list:
  479. """挂载USB设备"""
  480. usb_list = []
  481. usb_raw = run_cmd("lsusb")
  482. for line in usb_raw.splitlines():
  483. if line.strip():
  484. usb_list.append(line.strip())
  485. return usb_list
  486. def collect_all_info() -> dict:
  487. data = {
  488. "host_name": get_hostname(),
  489. "cpu": get_cpu_info(),
  490. "memory": get_memory_info(),
  491. "disk": get_disk_info(),
  492. "gpu": get_gpu_info(),
  493. "usb_devices": get_usb_devices()
  494. }
  495. # "network": get_network_info(),
  496. return data
  497. from rclpy.qos import QoSProfile, QoSReliabilityPolicy
  498. from ros2cli.node.strategy import NodeStrategy
  499. def get_all_nodes() -> list:
  500. """获取当前所有运行节点名称"""
  501. with NodeStrategy([]) as node:
  502. node_names = node.get_node_names_and_namespaces()
  503. nodes = [f"{ns}/{name}" if ns != "/" else f"/{name}" for name, ns in node_names]
  504. return nodes
  505. class ROS2TopicMonitor(Node):
  506. def __init__(self):
  507. super().__init__("ros2_topic_monitor")
  508. self.topic_subs = {} # 存储话题订阅器
  509. self.topic_data_cache = {} # 缓存最新话题消息数据
  510. def get_all_nodes_topics(self):
  511. """获取当前所有运行节点、所有话题+消息类型"""
  512. # 获取全部节点
  513. node_names = self.get_node_names()
  514. node_list = []
  515. for name in node_names:
  516. node_list.append({"node_name": name})
  517. # 获取所有话题及对应消息类型
  518. topic_info_list = []
  519. all_topics = self.get_topic_names_and_types()
  520. for topic_name, type_list in all_topics:
  521. topic_info_list.append({
  522. "topic_name": topic_name,
  523. "msg_types": type_list
  524. })
  525. return {
  526. "running_nodes": node_list,
  527. "all_topics": topic_info_list
  528. }
  529. def subscribe_topic(self, topic_name, msg_type_str):
  530. """动态订阅指定话题,解析消息类型"""
  531. if topic_name in self.topic_subs:
  532. return True
  533. try:
  534. # 拆分消息类型:如 std_msgs/msg/String
  535. pkg, msg_module, msg_cls = msg_type_str.split("/")
  536. import importlib
  537. msg_module_obj = importlib.import_module(f"{pkg}.{msg_module}")
  538. msg_class = getattr(msg_module_obj, msg_cls)
  539. except Exception as e:
  540. print(f"无法加载消息类型 {msg_type_str}: {str(e)}")
  541. return False
  542. # QoS配置,兼容大部分话题
  543. qos = QoSProfile(reliability=QoSReliabilityPolicy.RELIABLE, depth=10)
  544. def callback(msg):
  545. """话题消息回调,缓存最新数据"""
  546. self.topic_data_cache[topic_name] = self.msg_to_dict(msg)
  547. sub = self.create_subscription(msg_class, topic_name, callback, qos)
  548. self.topic_subs[topic_name] = sub
  549. print(f"已订阅话题: {topic_name}")
  550. return True
  551. def msg_to_dict(self, msg):
  552. """ROS消息对象转字典(递归解析嵌套消息)"""
  553. if hasattr(msg, "get_fields_and_field_types"):
  554. data = {}
  555. fields = msg.get_fields_and_field_types()
  556. for field_name, _ in fields.items():
  557. val = getattr(msg, field_name)
  558. # 递归处理嵌套消息
  559. if hasattr(val, "get_fields_and_field_types"):
  560. data[field_name] = self.msg_to_dict(val)
  561. elif isinstance(val, list):
  562. arr = []
  563. for item in val:
  564. if hasattr(item, "get_fields_and_field_types"):
  565. arr.append(self.msg_to_dict(item))
  566. else:
  567. arr.append(item)
  568. data[field_name] = arr
  569. else:
  570. data[field_name] = val
  571. return data
  572. return msg
  573. def get_topic_latest_data(self, topic_name):
  574. """获取指定话题最新缓存数据"""
  575. return self.topic_data_cache.get(topic_name, "暂无收到任何消息")
  576. def get_node_pub_sub_info(ros_node, target_node):
  577. """查询单个节点的发布、订阅话题"""
  578. # 拆分节点名与命名空间
  579. if "/" in target_node:
  580. parts = target_node.rsplit("/", 1)
  581. node_ns = parts[0] if parts[0] != "" else "/"
  582. node_name = parts[1]
  583. else:
  584. node_ns = "/"
  585. node_name = target_node
  586. # 传入 node_name + node_namespace 两个参数
  587. pub_topics = ros_node.get_publisher_names_and_types_by_node(node_name, node_ns)
  588. sub_topics = ros_node.get_subscriber_names_and_types_by_node(node_name, node_ns)
  589. return {
  590. "node_name": target_node,
  591. "publish_topics": [{"topic": t, "types": ty} for t, ty in pub_topics],
  592. "subscribe_topics": [{"topic": t, "types": ty} for t, ty in sub_topics]
  593. }
  594. def monitor(data=None):
  595. info = []
  596. all_nodes_topics = None
  597. sys_info = data.get("sys_info")
  598. ros2_info = data.get("ros2_info")
  599. ros2_node = data.get("ros2_node")
  600. ros2_topic = data.get("ros2_topic")
  601. # print(ros2_info, ros2_node, ros2_topic)
  602. if sys_info:
  603. sys_data = collect_all_info()
  604. info.append({"sys": sys_data})
  605. if ros2_info:
  606. result = subprocess.run("ros2 node list", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8")
  607. out_text = result.stdout
  608. lines = out_text.splitlines()
  609. info.append(lines)
  610. # info.append({"nodes": lines})
  611. # result = subprocess.run("ros2 topic list", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8")
  612. # out_text = result.stdout
  613. # lines = out_text.splitlines()
  614. # info.append({"topics": lines})
  615. # result = subprocess.run("ros2 service list", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8")
  616. # out_text = result.stdout
  617. # lines = out_text.splitlines()
  618. # info.append({"service": lines})
  619. if ros2_topic != None:
  620. result = subprocess.run(f"ros2 topic echo {ros2_topic}", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8")
  621. out_text = result.stdout
  622. # lines = out_text.splitlines()
  623. info.append({"topic": ros2_topic, "ctx": out_text})
  624. return info
  625. # if ros2_topic != "" != None and len(ros2_node) > 0:
  626. # return ""
  627. # rclpy.init()
  628. # monitor = ROS2TopicMonitor()
  629. # executor = rclpy.executors.MultiThreadedExecutor()
  630. # executor.add_node(monitor)
  631. # all_topic_data = monitor.get_all_nodes_topics()["all_topics"]
  632. # monitor.destroy_node()
  633. # rclpy.shutdown()
  634. # return all_topic_data
  635. # print(f"topics: {all_topic_data}")
  636. # match_topic = None
  637. # for t in all_topic_data:
  638. # if t["topic_name"] == ros2_topic:
  639. # match_topic = t
  640. # break
  641. # if not match_topic:
  642. # print(f"不存在话题 {ros2_topic}")
  643. # return "not exist"
  644. # # 订阅该话题所有消息类型
  645. # for msg_type in match_topic["msg_types"]:
  646. # monitor.subscribe_topic(ros2_topic, msg_type)
  647. # executor.spin_once(timeout_sec=0.1)
  648. # latest = monitor.get_topic_latest_data(ros2_topic)
  649. # # data_json = js.dumps({"topic": ros2_topic, "latest_data": latest}, ensure_ascii=False, indent=2)
  650. # monitor.destroy_node()
  651. # rclpy.shutdown()
  652. # return latest
  653. """
  654. """
  655. def get_files(target_dir, prefix=(), suffix=(), fd=2):
  656. """
  657. 读取指定目录下以bk开头,后缀为pgm、yaml、pcd的文件
  658. :param target_dir: 目标文件夹路径
  659. :return: 匹配的文件名列表
  660. """
  661. # 定义允许的后缀
  662. # suffix_list = (".pgm", ".yaml", ".pcd")
  663. match_files = []
  664. # 遍历目录下所有文件
  665. for filename in os.listdir(target_dir):
  666. # 拼接完整路径,判断是否为文件(排除文件夹)
  667. full_path = os.path.join(target_dir, filename)
  668. if (len(prefix) == 0 or filename.startswith(prefix)) and \
  669. (len(suffix) == 0 or filename.endswith(suffix)):
  670. if fd & 1 and os.path.isfile(full_path):
  671. match_files.append(filename[:filename.rfind(".")])
  672. if fd & 2 and os.path.isdir(full_path):
  673. match_files.append(filename)
  674. return match_files
  675. """
  676. """
  677. def map_manager(data=None):
  678. op = data.get("op")
  679. u = Utils()
  680. sh = r"/workspaces/srv/sh/9manage_map.sh"
  681. srv_dir = r"/workspaces/srv/app/static/imgs/"
  682. default_map = r"/workspaces/srv/app/static/js/default_map.json"
  683. hardware = r"/workspaces/srv/app/static/js/hardware.json"
  684. prefix = data.get("number")
  685. match op:
  686. case u.GET:
  687. # get all map infomation
  688. return get_files(srv_dir, prefix=("map"))
  689. case u.UPD:
  690. pass
  691. return "done"
  692. case u.CLS:
  693. # delete the map
  694. try:
  695. with open(default_map, "r+", encoding="utf-8") as f:
  696. r = f.read()
  697. r = "" if r == "" else js.loads(r)
  698. if r == prefix:
  699. f.write(r'{"number": ""}')
  700. f.close()
  701. with open(hardware, "r+", encoding="utf-8") as f:
  702. hardware_info = js.loads(f.read())
  703. subprocess.run(["python3", "/workspaces/ws/client/map_delete.py", \
  704. "--map", f"{prefix}", "--device", hardware_info.get("sn"), \
  705. "--secret", hardware_info.get("key")], shell=False)
  706. except FileNotFoundError:
  707. with open(default_map, "w+", encoding="utf-8") as f:
  708. f.write("")
  709. f.close()
  710. subprocess.run(["bash", sh, str(u.CLS), prefix], shell=False)
  711. return "done"
  712. case u.EXC:
  713. # set up default map
  714. # with open(default_map, "w+", encoding="utf-8") as f:
  715. # js.dump({"number": prefix}, f, ensure_ascii=False)
  716. # f.close()
  717. subprocess.run(["bash", sh, str(u.EXC), prefix], shell=False)
  718. return "done"
  719. case 5:
  720. ret = ""
  721. try:
  722. with open(default_map, "r+", encoding="utf-8") as f:
  723. ret = f.read()
  724. ret = "" if ret == "" else js.loads(ret)
  725. f.close()
  726. except FileNotFoundError:
  727. with open(default_map, "w+", encoding="utf-8") as f:
  728. f.write("")
  729. f.close()
  730. return ret
  731. return "none"
  732. """
  733. """
  734. def set_manager(data=None):
  735. u = Utils()
  736. op = data.get("op")
  737. sh = r"/workspaces/srv/sh/10manage_setting.sh"
  738. srv_dir = r"/workspaces/srv/app/static/js/"
  739. default_setting = r"/workspaces/srv/app/static/js/default_setting.json"
  740. prefix = data.get("number")
  741. match op:
  742. case u.GET:
  743. if prefix != None:
  744. return get_files(f"{srv_dir}{prefix}")
  745. else:
  746. # get all projects
  747. return get_files(srv_dir, prefix=("setting"))
  748. case u.UPD:
  749. file = data.get("file")
  750. if prefix != None and file != None:
  751. with open(f"{srv_dir}{prefix}/{file}", "w+", encoding="utf-8") as f:
  752. js.dump(data.get("setting"), f, ensure_ascii=False)
  753. ret = "Update"
  754. f.close()
  755. else:
  756. ret = "configuration number or file is none"
  757. case u.CLS:
  758. # delete the project
  759. try:
  760. with open(default_setting, "r+", encoding="utf-8") as f:
  761. r = f.read()
  762. r = "" if r == "" else js.loads(r)
  763. if r == prefix:
  764. f.write(r'{"number": ""}')
  765. f.close()
  766. except FileNotFoundError:
  767. with open(default_setting, "w+", encoding="utf-8") as f:
  768. f.write("")
  769. f.close()
  770. subprocess.run(["bash", sh, str(u.CLS), prefix], shell=False)
  771. return "done"
  772. case u.EXC:
  773. # set up default project
  774. subprocess.run(["bash", sh, str(u.EXC), prefix], shell=False)
  775. return "done"
  776. case 5:
  777. ret = ""
  778. try:
  779. with open(default_setting, "r+", encoding="utf-8") as f:
  780. ret = f.read()
  781. ret = "" if ret == "" else js.loads(ret)
  782. f.close()
  783. except FileNotFoundError:
  784. with open(default_setting, "w+", encoding="utf-8") as f:
  785. f.write("")
  786. f.close()
  787. return ret
  788. return "none"
  789. """
  790. """
  791. def vision(data=None):
  792. op = data.get("op")
  793. match op:
  794. case 5:
  795. # yolo
  796. subprocess.run(["bash", "/workspaces/srv/sh/11run_yolo_pose.sh"], shell=False)
  797. return "done"
  798. case 6:
  799. pass
  800. # mapping
  801. subprocess.run(["bash", "/workspaces/srv/sh/12start_rtab.sh"], shell=False)
  802. return "done"
  803. return "none"
  804. """
  805. """
  806. def recorder(data=None):
  807. op = data.get("op")
  808. u = Utils()
  809. number = data.get("number")
  810. srv_dir = r"/workspaces/srv/app/static/rec/"
  811. match op:
  812. case u.GET:
  813. return get_files(srv_dir, prefix=("nav_bag_"))
  814. case u.CLS:
  815. subprocess.run(["bash", "/workspaces/srv/sh/13recorder.sh", str(u.CLS), str(number)], shell=False)
  816. return "done"
  817. case 4:
  818. if number == None:
  819. subprocess.run(["bash", "/workspaces/srv/sh/13recorder.sh", "4"], shell=False)
  820. else:
  821. subprocess.run(["bash", "/workspaces/srv/sh/13recorder.sh", "4", str(number)], shell=False)
  822. return "done"
  823. case 5:
  824. subprocess.run(["bash", "/workspaces/srv/sh/13recorder.sh", "5"], shell=False)
  825. return "done"
  826. case 6:
  827. if number != None:
  828. with open(f"{srv_dir}{number}/schedule.json", "w+", encoding="utf-8") as f:
  829. js.dump(data.get("schedule"), f, ensure_ascii=False)
  830. f.close()
  831. return "done"
  832. return "none"
  833. async def websocket_client(payload=""):
  834. try:
  835. async with websockets.connect("http://127.0.0.1:9001") as websocket:
  836. # 向服务器发送消息
  837. await websocket.send(payload)
  838. # 接收来自服务器的消息
  839. resp = await websocket.recv()
  840. except Exception as e:
  841. print(f"{e}")