| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917 |
- import rclpy
- from rclpy.node import Node
- from rclpy.time import Duration
- from nav_msgs.msg import OccupancyGrid
- from geometry_msgs.msg import Twist, PoseWithCovarianceStamped
- import cv2
- import json as js
- from .utils import Utils
- import time, random, math
- import asyncio
- import websockets
- """
- """
- class MapDataSub(Node):
- mapdata = OccupancyGrid()
- posdata = PoseWithCovarianceStamped()
- def __init__(self):
- super().__init__("mapdata_sub")
- self.mapping_sub = self.create_subscription(
- OccupancyGrid,
- '/map',
- self.mapping_cbk,
- 10
- )
- self.pos_sub = self.create_subscription(
- PoseWithCovarianceStamped,
- '/pose',
- self.pos_cbk,
- 10
- )
-
- def mapping_cbk(self, msg):
- self.mapdata = msg
-
- def pos_cbk(self, msg):
- self.posdata = msg
- # def quaternion_to_yaw(qx: float, qy: float, qz: float, qw: float) -> float:
- # """四元数转偏航角yaw(rad)"""
- # siny_cosp = 2 * (qw * qz + qx * qy)
- # cosy_cosp = qw**2 + qx**2 - qy**2 - qz**2
- # yaw = math.atan2(siny_cosp, cosy_cosp)
- # return yaw
- def quaternion_to_yaw(qx: float, qy: float, qz: float, qw: float) -> float:
- """
- ROS标准四元数(x,y,z,w)转绕Z轴偏航角yaw
- 返回弧度,范围 [-π, π]
- """
- # 修正后的标准计算公式
- siny_cosp = 2.0 * (qw * qz + qx * qy)
- cosy_cosp = 1.0 - 2.0 * (qy ** 2 + qz ** 2)
- yaw = math.atan2(siny_cosp, cosy_cosp)
- return math.degrees(yaw)
- def mapdata_sub(args=None):
- rclpy.init(args=args)
- node = MapDataSub()
- rclpy.spin_once(node)
- res1 = node.mapdata
- res2 = node.posdata
- node.destroy_node()
- rclpy.shutdown()
- res = {}
- if res1 is not None:
- res.update({
- "width": res1.info.width,
- "height": res1.info.height,
- "x": res1.info.origin.position.x,
- "y": res1.info.origin.position.y,
- "z": res1.info.origin.position.z,
- "resolution": res1.info.resolution,
- "data": str(res1.data)
- })
- if res2 is not None:
- res.update({
- "cur_x": res2.pose.pose.position.x,
- "cur_y": res2.pose.pose.position.y,
- "yaw": quaternion_to_yaw(res2.pose.pose.orientation.x,
- res2.pose.pose.orientation.y,
- res2.pose.pose.orientation.z,
- res2.pose.pose.orientation.w)})
- return res
- """
- """
- def map_edit(data=None):
- number = data.get("number")
- map_path = "/workspaces/srv/app/static/imgs/"
- pgm_path = "/workspaces/nav_ws/src/classic_nav_bringup/map/map.pgm"
- dir = ""
- default_map = r"/workspaces/srv/app/static/js/default_map.json"
- try:
- with open(default_map, "r+", encoding="utf-8") as f:
- n = f.read()
- n = "" if n == "" else js.loads(n)
- if number == n.get("number"):
- dir = pgm_path
- f.close()
- except FileNotFoundError:
- with open(default_map, "w+", encoding="utf-8") as f:
- f.write("")
- f.close()
-
- # img = cv2.imread("/workspaces/nav_ws/src/classic_nav_bringup/map/map.pgm", cv2.IMREAD_UNCHANGED)
- if number == None or number == "":
- number = ""
- dir = pgm_path
- elif dir == "":
- dir = f"{map_path}{number}/map.pgm"
- srv_path = f"{map_path}{number}/map.pgm"
- img = cv2.imread(dir, cv2.IMREAD_UNCHANGED)
- if img is None:
- print("no pgm file")
- return "unsaved"
- if data is not None:
- for obs in data.get("obs"):
- op = obs[4]
- match op:
- case 4:
- cv2.rectangle(img, (obs[0], obs[1]), (obs[2], obs[3]), (0, 0, 0), -1, 8)
- case 5:
- cv2.line(img, (obs[0], obs[1]), (obs[2], obs[3]), (0, 0, 0), 3)
- for erase in data.get("erase"):
- op = erase[4]
- match op:
- case 4:
- cv2.rectangle(img, (erase[0], erase[1]), (erase[2], erase[3]), (255, 255, 255), -1, 8)
- case 5:
- cv2.line(img, (obs[0], obs[1]), (obs[2], obs[3]), (0, 0, 0), 3)
-
- # cv2.imwrite("/workspaces/nav_ws/src/classic_nav_bringup/map/map.pgm", img)
- cv2.imwrite(dir, img)
- cv2.imwrite(srv_path, img)
- # 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)
- return number
- def map_edit2(data=None):
- number = data.get("number")
- map_path = "/workspaces/srv/app/static/imgs/"
- # download: curl -o map.pgm http://localhost:5555/api/maps/Secure_911/pgm/map.pgm
- # subprocess.run(["curl", "-o", "map.pgm", f"http://localhost:5555/api/maps/{number}/pgm/map.pgm"], shell=False)
- # subprocess.run(["curl", "-o", "map.yaml", f"http://localhost:5555/api/maps/{number}/pgm/map.yaml"], shell=False)
- # draw
- # img = cv2.imread(f"{map_path}map.pgm", cv2.IMREAD_UNCHANGED)
- img = cv2.imread(f"{map_path}map.pgm", cv2.IMREAD_UNCHANGED)
- if img is None:
- print("no pgm file")
- return "unsaved"
- if data is not None:
- for obs in data.get("obs"):
- if len(obs) == 0:
- continue
- op = obs[4]
- match op:
- case 4:
- cv2.rectangle(img, (obs[0], obs[1]), (obs[2], obs[3]), (0, 0, 0), -1, 8)
- case 5:
- cv2.line(img, (obs[0], obs[1]), (obs[2], obs[3]), (0, 0, 0), 3)
- case 6:
- cv2.rectangle(img, (erase[0], erase[1]), (erase[2], erase[3]), (255, 255, 255), -1, 8)
- case 7:
- cv2.line(img, (obs[0], obs[1]), (obs[2], obs[3]), (255, 255, 255), 3)
- for erase in data.get("erase"):
- if len(erase) == 0:
- continue
- op = erase[4]
- match op:
- case 4:
- cv2.rectangle(img, (erase[0], erase[1]), (erase[2], erase[3]), (255, 255, 255), -1, 8)
- case 5:
- cv2.line(img, (obs[0], obs[1]), (obs[2], obs[3]), (255, 255, 255), 3)
- cv2.imwrite(f"{map_path}map.pgm", img)
- cv2.imwrite(f"{map_path}{number}/map.pgm", img)
- # upload: curl -X POST -F "pgm=@/path/to/your/map.pgm" -F "yaml=@/path/to/your/map.yaml" http://localhost:5000/upload_map
- 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)
- print(ret)
- subprocess.run(["convert", f"{map_path}{number}/map.pgm", f"{map_path}{number}/map.png"], shell=False)
- subprocess.run(["python3", "/workspacs/ws/client/map_save.py", "--map", f"{number}", "--dir", f"{map_path}{number}"], shell=False)
- return number
- # import serial
- # def mot_ctrl():
- # # ser = serial.Serial("/dev/ttyUSB1", 1_000_000, timeout=-1)
- # # if ser.isOpen():
- # # ser.write(bytes.fromhex(data.encode("utf-8").hex()))
- # # ser.close()
- # # return ""
-
- # ser = serial.Serial("/dev/ttyUSB1", 1_000_000, timeout=-1)
- # ret = ""
- # if ser.isOpen():
- # ser.write(bytes.fromhex(data.encode("utf-8").hex()))
- # ret = ser.readall()
- # ser.close()
- # return ret
- """
- """
- def station_edit(data=None):
- ret = ""
- if data is not None:
- u = Utils()
- op = data.get("op")
- number = data.get("number")
- if number == None or number == "":
- number = f"map{time.time()*1000:.0f}{random.randint(1000, 9999)}"
- dir = f"/workspaces/srv/app/static/imgs/{number}"
- if op == u.UPD and not os.path.exists(dir):
- os.mkdir(dir)
- subprocess.run(["bash", "/workspaces/srv/sh/9manage_map.sh", str(u.UPD), str(number)], shell=False)
- file_path = f"{dir}/stations.json"
- match op:
- case u.GET:
- try:
- with open(file_path, "r+", encoding="utf-8") as f:
- ret = f.read()
- ret = "" if ret == "" else js.loads(ret)
- f.close()
- except FileNotFoundError:
- with open(file_path, "w+", encoding="utf-8") as f:
- f.write("")
- f.close()
- case u.UPD:
- with open(file_path, "w+", encoding="utf-8") as f:
- js.dump(data.get("stations"), f, ensure_ascii=False)
- ret = "Update"
- f.close()
- subprocess.run(["python3", "/workspacs/ws/client/map_save.py", "--map", f"{number}", "--dir", f"{dir}"], shell=False)
- case u.CLS:
- with open(file_path, "w+", encoding="utf-8") as f:
- f.write("")
- ret = "Clear"
- f.close()
- subprocess.run(["python3", "/workspacs/ws/client/map_save.py", "--map", f"{number}", "--dir", f"{dir}"], shell=False)
- return {"ret": ret, "number": number}
- def schedule(data=None):
- ret = ""
- if data is not None:
- u = Utils()
- op = data.get("op")
- number = data.get("number")
- file_path = f"/workspaces/srv/app/static/imgs/{number}/sechudle.json"
- match op:
- case u.GET:
- try:
- with open(file_path, "r", encoding="utf-8") as f:
- ret = f.read()
- ret = "" if ret == "" else js.loads(ret)
- f.close()
- except FileNotFoundError:
- with open(file_path, "w+", encoding="utf-8") as f:
- f.write("")
- f.close()
- case u.UPD:
- with open(file_path, "w+", encoding="utf-8") as f:
- js.dump(data.get("schedule"), f, ensure_ascii=False)
- ret = "Update"
- f.close()
- case u.CLS:
- with open(file_path, "w+", encoding="utf-8") as f:
- f.write("")
- ret = "Clear"
- f.close()
- case u.EXC:
- try:
- with open(file_path, "r", encoding="utf-8") as f:
- payloads = f.read()
- f.close()
- except FileNotFoundError:
- ret = "No schedule"
- return ret
- """
- """
- def upgrade_info(data=None):
- file_path = f"/workspaces/srv/app/static/templates/{data.get('info')}"
- ret = ""
- try:
- with open(file_path, "r", encoding="utf-8") as f:
- ret = f.read()
- f.close()
- except FileNotFoundError:
- with open(file_path, "w+", encoding="utf-8") as f:
- f.write("0")
- f.close()
- return ret
- """
- """
- import os, subprocess
- import platform
- from datetime import datetime as dt
- def get_file_create_time(file_path: str) -> str:
- """兼容多系统获取文件创建时间,返回格式化字符串"""
- stat = os.stat(file_path)
- sys_name = platform.system()
- if sys_name == "Windows":
- create_timestamp = stat.st_ctime
- elif sys_name == "Darwin": # macOS
- create_timestamp = stat.st_birthtime
- else: # Linux 无原生创建时间,改用修改时间替代
- create_timestamp = stat.st_mtime
- # 格式化时间
- create_time = dt.fromtimestamp(create_timestamp).strftime("%Y-%m-%d %H:%M:%S")
- return create_time
- def scan_log_files(root_dir: str):
- """递归扫描所有.log文件,组装数据列表"""
- result_list = []
- # 遍历目录树
- for dirpath, _, filenames in os.walk(root_dir):
- for filename in filenames:
- if filename.lower().endswith(".log"):
- file_full_path = os.path.join(dirpath, filename)
- # 相对路径:目录名/文件名
- rel_path = os.path.relpath(file_full_path, root_dir).replace(os.sep, "/")
- # content = "..."
- # file_disk_size = os.path.getsize(file_full_path)
- # 读取文件内容(捕获编码异常)
- try:
- with open(file_full_path, "r", encoding="utf-8") as f:
- content = f.read(102_400)
- except UnicodeDecodeError:
- with open(file_full_path, "r", encoding="gbk", errors="ignore") as f:
- content = f.read(102_400)
- # 获取创建时间
- create_time = get_file_create_time(file_full_path)
- # 组装单条数据
- file_info = {
- "file_path": rel_path, # 目录名称/文件名称
- "file_content": content, # 文件内容
- "file_create_time": create_time # 文件创建时间
- }
- result_list.append(file_info)
- return result_list
- def logger(data=None):
- op = data.get("op")
- u = Utils()
- # file_path = r"/workspaces/log/"
- file_path = r"/workspaces/srv/app/static/rec"
- hardware_path = r"/workspaces/srv/app/static/js/hardware.json"
- match op:
- case u.GET:
- log_data = scan_log_files(file_path)
- return log_data
- json_str = js.dumps(log_data, ensure_ascii=False, indent=2)
- return json_str
- case u.UPD:
- number = data.get("number")
- log = data.get("log")
- # UPLOAD
- try:
- with open(hardware_path, "r+", encoding="utf-8") as f:
- hardware_info = js.loads(f.read())
- f.close()
- sn, key = hardware_info.get("sn"), hardware_info.get("key")
- subprocess.run(["python3", "/workspaces/ws/client/nav_recoder_client", "--action",\
- "upload", "--device", f"{sn}", "--secret", f"{key}", "--map", f"{log.get()}",\
- "--batch-id", f"{log.get()}", "--sites", f"{log.get()}", "--path", f"{log.get()}",\
- "--log", "", "--base"])
-
- log["tag"] = "upload"
- except:
- log["tag"] = ""
- with open(f"{file_path}/{number}.json", "w+", encoding="utf-8") as f:
- js.dumps(log, f, ensure_ascii=False)
- f.close()
- case u.CLS:
- subprocess.run(["bash", "/workspaces/srv/sh/8clear_log.sh", str(data.get("number"))], shell=False)
- return "done"
- case _:
- return ""
- """
- """
- import socket
- import psutil
- from pywifi import PyWiFi, const
- def run_cmd(cmd: str) -> str:
- """执行shell命令,返回输出文本"""
- try:
- res = subprocess.check_output(cmd, shell=True, text=True, stderr=subprocess.STDOUT)
- return res.strip()
- except subprocess.CalledProcessError:
- return ""
- def get_hostname() -> str:
- """主机名"""
- return socket.gethostname()
- def get_cpu_info() -> dict:
- """CPU信息:核心数、使用率、温度"""
- cpu_count = psutil.cpu_count(logical=True)
- cpu_phys_count = psutil.cpu_count(logical=False) or cpu_count
- cpu_percent = psutil.cpu_percent(interval=0.5)
- cpu_freq = psutil.cpu_freq()
- # CPU温度
- temp_text = run_cmd("sensors")
- cpu_temp = []
- for line in temp_text.splitlines():
- if "Core" in line and "+" in line:
- cpu_temp.append(line.strip())
- return {
- "physical_core": cpu_phys_count,
- "logical_core": cpu_count,
- "usage_percent": cpu_percent,
- "current_freq_mhz": round(cpu_freq.current, 2) if cpu_freq else None,
- "max_freq_mhz": round(cpu_freq.max, 2) if cpu_freq else None,
- "temperature": cpu_temp
- }
- def get_memory_info() -> dict:
- """内存信息"""
- mem = psutil.virtual_memory()
- swap = psutil.swap_memory()
- def mb(val): return round(val / 1024 / 1024, 2)
- return {
- "total_mb": mb(mem.total),
- "used_mb": mb(mem.used),
- "free_mb": mb(mem.free),
- "available_mb": mb(mem.available),
- "usage_percent": mem.percent,
- "swap_total_mb": mb(swap.total),
- "swap_used_mb": mb(swap.used)
- }
- def get_disk_info() -> list:
- """磁盘分区挂载信息"""
- disks = []
- for part in psutil.disk_partitions(all=False):
- try:
- usage = psutil.disk_usage(part.mountpoint)
- def gb(val): return round(val / 1024 / 1024 / 1024, 2)
- disks.append({
- "device": part.device,
- "mount_point": part.mountpoint,
- "fstype": part.fstype,
- "total_gb": gb(usage.total),
- "used_gb": gb(usage.used),
- "free_gb": gb(usage.free),
- "usage_percent": usage.percent
- })
- except PermissionError:
- continue
- return disks
- def get_gpu_info() -> list:
- """GPU信息(nvidia显卡,无nvidia-smi返回空)"""
- gpu_list = []
- gpu_raw = run_cmd("nvidia-smi --query-gpu=name,memory.total,memory.used,temperature.gpu --format=csv,noheader,nounits")
- if not gpu_raw:
- return gpu_list
- for line in gpu_raw.splitlines():
- parts = [p.strip() for p in line.split(",")]
- if len(parts) == 4:
- gpu_list.append({
- "name": parts[0],
- "total_memory_mb": parts[1],
- "used_memory_mb": parts[2],
- "temp_c": parts[3]
- })
- return gpu_list
- def get_network_info() -> list:
- """网卡:MAC、IP、WIFI名称、信号强度"""
- net_info = []
- wifi = PyWiFi()
-
- interfaces = wifi.interfaces()
- # 获取WIFI当前连接信息
- wifi_signal_map = {}
- for iface in interfaces:
- if iface.status() == const.IFACE_CONNECTED:
- profile = iface.network_profiles()[0] if iface.network_profiles() else None
- sig = iface.signal()
- ssid = profile.ssid if profile else ""
- wifi_signal_map[iface.name()] = {
- "ssid": ssid,
- "signal_dbm": sig
- }
- # 遍历网卡
- for name, addrs in psutil.net_if_addrs().items():
- mac = ""
- ipv4 = ""
- for addr in addrs:
- if addr.family == psutil.AF_LINK:
- mac = addr.address
- elif addr.family == socket.AF_INET:
- ipv4 = addr.address
- if not mac:
- continue
- wifi_data = wifi_signal_map.get(name, {})
- net_info.append({
- "nic_name": name,
- "mac_address": mac,
- "ipv4": ipv4,
- "wifi_ssid": wifi_data.get("ssid", ""),
- "wifi_signal_dbm": wifi_data.get("signal_dbm", None)
- })
- return net_info
- def get_usb_devices() -> list:
- """挂载USB设备"""
- usb_list = []
- usb_raw = run_cmd("lsusb")
- for line in usb_raw.splitlines():
- if line.strip():
- usb_list.append(line.strip())
- return usb_list
- def collect_all_info() -> dict:
- data = {
- "host_name": get_hostname(),
- "cpu": get_cpu_info(),
- "memory": get_memory_info(),
- "disk": get_disk_info(),
- "gpu": get_gpu_info(),
- "usb_devices": get_usb_devices()
- }
- # "network": get_network_info(),
- return data
- from rclpy.qos import QoSProfile, QoSReliabilityPolicy
- from ros2cli.node.strategy import NodeStrategy
- def get_all_nodes() -> list:
- """获取当前所有运行节点名称"""
- with NodeStrategy([]) as node:
- node_names = node.get_node_names_and_namespaces()
- nodes = [f"{ns}/{name}" if ns != "/" else f"/{name}" for name, ns in node_names]
- return nodes
- class ROS2TopicMonitor(Node):
- def __init__(self):
- super().__init__("ros2_topic_monitor")
- self.topic_subs = {} # 存储话题订阅器
- self.topic_data_cache = {} # 缓存最新话题消息数据
- def get_all_nodes_topics(self):
- """获取当前所有运行节点、所有话题+消息类型"""
- # 获取全部节点
- node_names = self.get_node_names()
- node_list = []
- for name in node_names:
- node_list.append({"node_name": name})
- # 获取所有话题及对应消息类型
- topic_info_list = []
- all_topics = self.get_topic_names_and_types()
- for topic_name, type_list in all_topics:
- topic_info_list.append({
- "topic_name": topic_name,
- "msg_types": type_list
- })
- return {
- "running_nodes": node_list,
- "all_topics": topic_info_list
- }
- def subscribe_topic(self, topic_name, msg_type_str):
- """动态订阅指定话题,解析消息类型"""
- if topic_name in self.topic_subs:
- return True
- try:
- # 拆分消息类型:如 std_msgs/msg/String
- pkg, msg_module, msg_cls = msg_type_str.split("/")
- import importlib
- msg_module_obj = importlib.import_module(f"{pkg}.{msg_module}")
- msg_class = getattr(msg_module_obj, msg_cls)
- except Exception as e:
- print(f"无法加载消息类型 {msg_type_str}: {str(e)}")
- return False
- # QoS配置,兼容大部分话题
- qos = QoSProfile(reliability=QoSReliabilityPolicy.RELIABLE, depth=10)
- def callback(msg):
- """话题消息回调,缓存最新数据"""
- self.topic_data_cache[topic_name] = self.msg_to_dict(msg)
- sub = self.create_subscription(msg_class, topic_name, callback, qos)
- self.topic_subs[topic_name] = sub
- print(f"已订阅话题: {topic_name}")
- return True
- def msg_to_dict(self, msg):
- """ROS消息对象转字典(递归解析嵌套消息)"""
- if hasattr(msg, "get_fields_and_field_types"):
- data = {}
- fields = msg.get_fields_and_field_types()
- for field_name, _ in fields.items():
- val = getattr(msg, field_name)
- # 递归处理嵌套消息
- if hasattr(val, "get_fields_and_field_types"):
- data[field_name] = self.msg_to_dict(val)
- elif isinstance(val, list):
- arr = []
- for item in val:
- if hasattr(item, "get_fields_and_field_types"):
- arr.append(self.msg_to_dict(item))
- else:
- arr.append(item)
- data[field_name] = arr
- else:
- data[field_name] = val
- return data
- return msg
- def get_topic_latest_data(self, topic_name):
- """获取指定话题最新缓存数据"""
- return self.topic_data_cache.get(topic_name, "暂无收到任何消息")
-
- def get_node_pub_sub_info(ros_node, target_node):
- """查询单个节点的发布、订阅话题"""
- # 拆分节点名与命名空间
- if "/" in target_node:
- parts = target_node.rsplit("/", 1)
- node_ns = parts[0] if parts[0] != "" else "/"
- node_name = parts[1]
- else:
- node_ns = "/"
- node_name = target_node
- # 传入 node_name + node_namespace 两个参数
- pub_topics = ros_node.get_publisher_names_and_types_by_node(node_name, node_ns)
- sub_topics = ros_node.get_subscriber_names_and_types_by_node(node_name, node_ns)
- return {
- "node_name": target_node,
- "publish_topics": [{"topic": t, "types": ty} for t, ty in pub_topics],
- "subscribe_topics": [{"topic": t, "types": ty} for t, ty in sub_topics]
- }
- def monitor(data=None):
- info = []
- all_nodes_topics = None
- sys_info = data.get("sys_info")
- ros2_info = data.get("ros2_info")
- ros2_node = data.get("ros2_node")
- ros2_topic = data.get("ros2_topic")
- # print(ros2_info, ros2_node, ros2_topic)
- if sys_info:
- sys_data = collect_all_info()
- info.append({"sys": sys_data})
- if ros2_info:
- result = subprocess.run("ros2 node list", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8")
- out_text = result.stdout
- lines = out_text.splitlines()
- info.append(lines)
- # info.append({"nodes": lines})
- # result = subprocess.run("ros2 topic list", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8")
- # out_text = result.stdout
- # lines = out_text.splitlines()
- # info.append({"topics": lines})
- # result = subprocess.run("ros2 service list", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8")
- # out_text = result.stdout
- # lines = out_text.splitlines()
- # info.append({"service": lines})
- if ros2_topic != None:
- result = subprocess.run(f"ros2 topic echo {ros2_topic}", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8")
- out_text = result.stdout
- # lines = out_text.splitlines()
- info.append({"topic": ros2_topic, "ctx": out_text})
-
- return info
- # if ros2_topic != "" != None and len(ros2_node) > 0:
- # return ""
- # rclpy.init()
- # monitor = ROS2TopicMonitor()
- # executor = rclpy.executors.MultiThreadedExecutor()
- # executor.add_node(monitor)
- # all_topic_data = monitor.get_all_nodes_topics()["all_topics"]
- # monitor.destroy_node()
- # rclpy.shutdown()
- # return all_topic_data
-
- # print(f"topics: {all_topic_data}")
- # match_topic = None
- # for t in all_topic_data:
- # if t["topic_name"] == ros2_topic:
- # match_topic = t
- # break
- # if not match_topic:
-
- # print(f"不存在话题 {ros2_topic}")
- # return "not exist"
- # # 订阅该话题所有消息类型
- # for msg_type in match_topic["msg_types"]:
- # monitor.subscribe_topic(ros2_topic, msg_type)
- # executor.spin_once(timeout_sec=0.1)
- # latest = monitor.get_topic_latest_data(ros2_topic)
- # # data_json = js.dumps({"topic": ros2_topic, "latest_data": latest}, ensure_ascii=False, indent=2)
- # monitor.destroy_node()
- # rclpy.shutdown()
- # return latest
- """
- """
- def get_files(target_dir, prefix=(), suffix=(), fd=2):
- """
- 读取指定目录下以bk开头,后缀为pgm、yaml、pcd的文件
- :param target_dir: 目标文件夹路径
- :return: 匹配的文件名列表
- """
- # 定义允许的后缀
- # suffix_list = (".pgm", ".yaml", ".pcd")
- match_files = []
- # 遍历目录下所有文件
- for filename in os.listdir(target_dir):
- # 拼接完整路径,判断是否为文件(排除文件夹)
- full_path = os.path.join(target_dir, filename)
- if (len(prefix) == 0 or filename.startswith(prefix)) and \
- (len(suffix) == 0 or filename.endswith(suffix)):
- if fd & 1 and os.path.isfile(full_path):
- match_files.append(filename[:filename.rfind(".")])
- if fd & 2 and os.path.isdir(full_path):
- match_files.append(filename)
- return match_files
- """
- """
- def map_manager(data=None):
- op = data.get("op")
- u = Utils()
- sh = r"/workspaces/srv/sh/9manage_map.sh"
- srv_dir = r"/workspaces/srv/app/static/imgs/"
- default_map = r"/workspaces/srv/app/static/js/default_map.json"
- hardware = r"/workspaces/srv/app/static/js/hardware.json"
- prefix = data.get("number")
- match op:
- case u.GET:
- # get all map infomation
- return get_files(srv_dir, prefix=("map"))
- case u.UPD:
- pass
- return "done"
- case u.CLS:
- # delete the map
- try:
- with open(default_map, "r+", encoding="utf-8") as f:
- r = f.read()
- r = "" if r == "" else js.loads(r)
- if r == prefix:
- f.write(r'{"number": ""}')
- f.close()
- with open(hardware, "r+", encoding="utf-8") as f:
- hardware_info = js.loads(f.read())
- subprocess.run(["python3", "/workspaces/ws/client/map_delete.py", \
- "--map", f"{prefix}", "--device", hardware_info.get("sn"), \
- "--secret", hardware_info.get("key")], shell=False)
- except FileNotFoundError:
- with open(default_map, "w+", encoding="utf-8") as f:
- f.write("")
- f.close()
- subprocess.run(["bash", sh, str(u.CLS), prefix], shell=False)
- return "done"
-
- case u.EXC:
- # set up default map
- # with open(default_map, "w+", encoding="utf-8") as f:
- # js.dump({"number": prefix}, f, ensure_ascii=False)
- # f.close()
- subprocess.run(["bash", sh, str(u.EXC), prefix], shell=False)
- return "done"
- case 5:
- ret = ""
- try:
- with open(default_map, "r+", encoding="utf-8") as f:
- ret = f.read()
- ret = "" if ret == "" else js.loads(ret)
- f.close()
- except FileNotFoundError:
- with open(default_map, "w+", encoding="utf-8") as f:
- f.write("")
- f.close()
- return ret
- return "none"
- """
- """
- def set_manager(data=None):
- u = Utils()
- op = data.get("op")
- sh = r"/workspaces/srv/sh/10manage_setting.sh"
- srv_dir = r"/workspaces/srv/app/static/js/"
- default_setting = r"/workspaces/srv/app/static/js/default_setting.json"
- prefix = data.get("number")
- match op:
- case u.GET:
- if prefix != None:
- return get_files(f"{srv_dir}{prefix}")
- else:
- # get all projects
- return get_files(srv_dir, prefix=("setting"))
- case u.UPD:
- file = data.get("file")
- if prefix != None and file != None:
- with open(f"{srv_dir}{prefix}/{file}", "w+", encoding="utf-8") as f:
- js.dump(data.get("setting"), f, ensure_ascii=False)
- ret = "Update"
- f.close()
- else:
- ret = "configuration number or file is none"
- case u.CLS:
- # delete the project
- try:
- with open(default_setting, "r+", encoding="utf-8") as f:
- r = f.read()
- r = "" if r == "" else js.loads(r)
- if r == prefix:
- f.write(r'{"number": ""}')
- f.close()
- except FileNotFoundError:
- with open(default_setting, "w+", encoding="utf-8") as f:
- f.write("")
- f.close()
- subprocess.run(["bash", sh, str(u.CLS), prefix], shell=False)
- return "done"
- case u.EXC:
- # set up default project
- subprocess.run(["bash", sh, str(u.EXC), prefix], shell=False)
- return "done"
- case 5:
- ret = ""
- try:
- with open(default_setting, "r+", encoding="utf-8") as f:
- ret = f.read()
- ret = "" if ret == "" else js.loads(ret)
- f.close()
- except FileNotFoundError:
- with open(default_setting, "w+", encoding="utf-8") as f:
- f.write("")
- f.close()
- return ret
- return "none"
- """
- """
- def vision(data=None):
- op = data.get("op")
- match op:
- case 5:
- # yolo
- subprocess.run(["bash", "/workspaces/srv/sh/11run_yolo_pose.sh"], shell=False)
- return "done"
- case 6:
- pass
- # mapping
- subprocess.run(["bash", "/workspaces/srv/sh/12start_rtab.sh"], shell=False)
- return "done"
- return "none"
- """
- """
- def recorder(data=None):
- op = data.get("op")
- u = Utils()
- number = data.get("number")
- srv_dir = r"/workspaces/srv/app/static/rec/"
- match op:
- case u.GET:
- return get_files(srv_dir, prefix=("nav_bag_"))
- case u.CLS:
- subprocess.run(["bash", "/workspaces/srv/sh/13recorder.sh", str(u.CLS), str(number)], shell=False)
- return "done"
- case 4:
- if number == None:
- subprocess.run(["bash", "/workspaces/srv/sh/13recorder.sh", "4"], shell=False)
- else:
- subprocess.run(["bash", "/workspaces/srv/sh/13recorder.sh", "4", str(number)], shell=False)
- return "done"
- case 5:
- subprocess.run(["bash", "/workspaces/srv/sh/13recorder.sh", "5"], shell=False)
- return "done"
- case 6:
- if number != None:
- with open(f"{srv_dir}{number}/schedule.json", "w+", encoding="utf-8") as f:
- js.dump(data.get("schedule"), f, ensure_ascii=False)
- f.close()
- return "done"
- return "none"
-
- async def websocket_client(payload=""):
- try:
- async with websockets.connect("http://127.0.0.1:9001") as websocket:
- # 向服务器发送消息
- await websocket.send(payload)
- # 接收来自服务器的消息
- resp = await websocket.recv()
- except Exception as e:
- print(f"{e}")
|