am-freescan/scripts/robot_simulator.py

471 lines
22 KiB
Python
Raw Normal View History

2026-10-22 16:18:37 +08:00
"""Opt-in loopback AGV fixture. Owns only explicitly marked rows in am-freescan.
No application runtime or original CMVR source is replaced. The existing Java
edge client talks to this process over the original protobuf/gRPC protocol.
"""
from __future__ import annotations
import argparse
import concurrent.futures
from datetime import datetime, timedelta, timezone
import hashlib
import importlib.metadata
import json
import math
import os
from pathlib import Path
import subprocess
import sys
import threading
import time
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / '.tools/python'))
LOCAL = ROOT / '.local/simulator'
SETTINGS = LOCAL / 'settings.json'
STATUS = LOCAL / 'status.json'
STOP = LOCAL / 'stop.request'
ROBOT_ID = 'am-freescan-sim-robot'
DEVICE_ID = 'am-freescan-sim-agv'
OWNER = 'freescan-simulator-v1'
DESCRIPTION = 'SIMULATED / 模拟测试资源:仅本机软件响应,不连接真实硬件'
DEFAULT_PORT = 58071
def read_json(path, default=None):
return json.loads(path.read_text(encoding='utf-8-sig')) if path.exists() else default
def write_json(path, data):
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(path.name + '.' + uuid.uuid4().hex + '.tmp')
try:
temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding='utf-8')
# Windows readers may temporarily disallow replacing an open file.
for attempt in range(50):
try:
temporary.replace(path)
break
except PermissionError:
if attempt == 49:
raise
time.sleep(0.05)
finally:
temporary.unlink(missing_ok=True)
class SimulatedAgv:
"""Small deterministic software world, never an inferred physical result."""
def __init__(self):
self.pose = (0.0, 0.0, 0.0)
self.progress = 0.0
self.navigation_state = 0
self.estop = False
self.message = 'SIMULATED: ready'
self.station = 'SIM-HOME'
self.stations = {'SIM-HOME': (0.0, 0.0, 0.0), 'SIM-STATION-1': (1.0, 1.0, 0.0)}
self.lock = threading.RLock()
def navigate(self, x, y, theta):
values = tuple(float(v) for v in (x, y, theta))
if not all(math.isfinite(v) for v in values):
raise ValueError('模拟坐标必须为有限数值')
with self.lock:
if self.estop:
raise ValueError('模拟AGV已急停,请先清除故障')
self.pose = values
self.navigation_state, self.progress = 4, 1.0
self.message = 'SIMULATED: simulated destination reached; no physical motion'
def navigate_station(self, station):
if station not in self.stations:
raise ValueError('模拟站点不存在:' + station)
self.navigate(*self.stations[station])
self.station = station
def emergency_stop(self):
with self.lock:
self.estop = True
self.navigation_state = 6
self.message = 'SIMULATED: emergency stop'
def clear_fault(self):
with self.lock:
self.estop = False
self.navigation_state = 0
self.message = 'SIMULATED: ready'
def protocol():
"""Generate bindings only in the ignored local fixture folder."""
import grpc_tools
from grpc_tools import protoc
source = ROOT / 'am-backend/yudao-module-cmvr/src/main/proto'
files = ['cmvr/api/common.proto', 'cmvr/msgs/agv.proto',
'cmvr/api/agv_command.proto', 'cmvr/api/agv_service.proto',
'cmvr/api/arm_command.proto', 'cmvr/api/system_command.proto',
'cmvr/api/system_service.proto']
output = LOCAL / 'proto'
output.mkdir(parents=True, exist_ok=True)
digest = hashlib.sha256(b''.join((source / name).read_bytes() for name in files)
+ importlib.metadata.version('grpcio-tools').encode()).hexdigest()
marker = output / 'bindings.sha256'
if not marker.exists() or marker.read_text() != digest:
includes = Path(grpc_tools.__file__).parent / '_proto'
result = protoc.main(['protoc', '-I' + str(source), '-I' + str(includes),
'--python_out=' + str(output), '--grpc_python_out=' + str(output)] + files)
if result:
raise RuntimeError('模拟器protobuf生成失败')
marker.write_text(digest)
if str(output) not in sys.path:
sys.path.insert(0, str(output))
from cmvr.api import common_pb2, agv_command_pb2, agv_service_pb2_grpc
from cmvr.msgs import agv_pb2
return common_pb2, agv_command_pb2, agv_service_pb2_grpc, agv_pb2
def create_grpc_server(port, world):
import grpc
common, command, service, message = protocol()
from cmvr.api import system_command_pb2 as system_command, system_service_pb2_grpc as system_service
def header(success=True, detail=''):
value = common.CommandHeader.Feedback(success=success, error_message=detail)
value.timestamp.GetCurrentTime()
return value
class AgvService(service.AgvServiceServicer):
def reply(self, request, feedback_type, action=None, **payload):
def result(success=True, detail='', **values):
response_header = header(success, detail)
return response_header if feedback_type is common.CommandHeader.Feedback else feedback_type(header=response_header, **values)
target = request.device_id if isinstance(request, common.CommandHeader.Request) else request.header.device_id
if target != DEVICE_ID:
return result(False, 'SIMULATED: unknown device ID')
try:
with world.lock:
if action:
action()
values = {name: value() if callable(value) else value for name, value in payload.items()}
return result(**values)
except ValueError as error:
return result(False, 'SIMULATED: ' + str(error))
def getRuntimeState(self, request, context):
return self.reply(request, command.AgvRuntimeStateCommand.Feedback, state=lambda:
message.AgvRuntimeState(timestamp=time.time(), mode=5 if world.estop else 2,
connected=True, localized=True, moving=False, fault=False, emergency_stopped=world.estop,
pose=message.AgvPose2d(x=world.pose[0], y=world.pose[1], theta=world.pose[2]),
velocity=message.AgvVelocity(), battery=message.AgvBatteryState(percentage=1.0),
current_map='SIM-MAP', current_station=world.station, last_error=world.message))
def getNavigationStatus(self, request, context):
return self.reply(request, command.AgvNavigationStatusCommand.Feedback, status=lambda:
message.AgvNavigationStatus(state=world.navigation_state, progress=world.progress, message=world.message))
def navigateToPose(self, request, context):
return self.reply(request, command.AgvNavigateToPoseCommand.Feedback,
lambda: world.navigate(request.pose.x, request.pose.y, request.pose.theta))
def relocalize(self, request, context):
return self.reply(request, command.AgvRelocalizeCommand.Feedback,
lambda: world.navigate(request.pose.x, request.pose.y, request.pose.theta))
def navigateToStation(self, request, context):
return self.reply(request, command.AgvNavigateToStationCommand.Feedback,
lambda: world.navigate_station(request.station_id))
def followPath(self, request, context):
def follow():
if not request.path:
raise ValueError('模拟导航路径不能为空')
for segment in request.path:
if segment.source_station not in world.stations or segment.target_station not in world.stations:
raise ValueError('模拟路径包含未知站点')
world.navigate_station(request.path[-1].target_station)
return self.reply(request, command.AgvFollowPathCommand.Feedback, follow)
def emergencyStop(self, request, context):
return self.reply(request, common.CommandHeader.Feedback, world.emergency_stop)
def clearFault(self, request, context):
return self.reply(request, common.CommandHeader.Feedback, world.clear_fault)
def cancelNavigation(self, request, context):
def cancel():
world.navigation_state = 6
world.message = 'SIMULATED: navigation cancelled'
return self.reply(request, common.CommandHeader.Feedback, cancel)
def pauseNavigation(self, request, context):
def pause():
if world.navigation_state in (1, 2):
world.navigation_state = 3
return self.reply(request, common.CommandHeader.Feedback, pause)
def resumeNavigation(self, request, context):
def resume():
if world.navigation_state == 3:
world.navigation_state = 4
world.progress = 1.0
return self.reply(request, common.CommandHeader.Feedback, resume)
def listMaps(self, request, context):
return self.reply(request, command.AgvListMapsCommand.Feedback, maps=['SIM-MAP'])
def listStations(self, request, context):
return self.reply(request, command.AgvListStationsCommand.Feedback, stations=lambda: [
message.AgvStation(id=name, type='SIMULATED', description=DESCRIPTION,
pose=message.AgvPose2d(x=pose[0], y=pose[1], theta=pose[2])) for name, pose in world.stations.items()])
class SystemService(system_service.SystemServiceServicer):
def StopAll(self, request, context):
# Original System StopAll targets the whole robot with an empty
# device ID. A named target must still be this fixture's AGV.
if request.header.device_id not in ('', DEVICE_ID):
return system_command.StopAllCommand.Feedback(
header=header(False, 'SIMULATED: unknown device ID; nothing stopped'))
with world.lock:
world.navigation_state, world.progress = 6, 0.0
world.message = 'SIMULATED: all simulated motion stopped; no physical hardware controlled'
return system_command.StopAllCommand.Feedback(header=header(True, world.message))
def GetSystemInfo(self, request, context):
return system_command.GetSystemInfoCommand.Feedback(
header=header(True, 'SIMULATED: local software fixture'), system_name=ROBOT_ID,
version='SIMULATED-v1', description=DESCRIPTION, os='SIMULATED', architecture='software-only')
def GetSystemStatus(self, request, context):
return system_command.GetSystemStatusCommand.Feedback(
header=header(True, 'SIMULATED: inventory contains only the simulated AGV'),
device_list=[system_command.DeviceList(device_id=DEVICE_ID, device_type=system_command.AGV)])
# UpdateParams/ExecuteActionQueue intentionally retain UNIMPLEMENTED.
# This simulator has no real arm, scanner, or physical parameters.
server = grpc.server(concurrent.futures.ThreadPoolExecutor(max_workers=4),
options=[('grpc.so_reuseport', 0)])
service.add_AgvServiceServicer_to_server(AgvService(), server)
system_service.add_SystemServiceServicer_to_server(SystemService(), server)
bound = server.add_insecure_port('127.0.0.1:' + str(port))
if not bound:
raise RuntimeError('模拟器本机端口被占用:' + str(port))
return server, bound
class ResourceStore:
def __init__(self):
from bootstrap_db import validate_target, META, OWNER as DATABASE_OWNER
import pymysql
config = read_json(ROOT / '.local/runtime.json')['mysql']
validate_target(config)
self.connection = pymysql.connect(host=config['host'], port=int(config.get('port', 3306)),
user=config['user'], password=config['password'], database=config['database'],
charset='utf8mb4', autocommit=False, cursorclass=pymysql.cursors.DictCursor,
connect_timeout=5, read_timeout=5, write_timeout=5)
with self.connection.cursor() as cursor:
cursor.execute('SELECT value FROM ' + META + ' WHERE name=%s', ('owner',))
row = cursor.fetchone()
if not row or row['value'] != DATABASE_OWNER:
raise RuntimeError('目标数据库归属验证失败')
self.connection.commit()
def cursor(self):
self.connection.ping(reconnect=False)
return self.connection.cursor()
def provision(self):
from bootstrap_db import insert_new
with self.cursor() as cursor:
cursor.execute('SELECT * FROM iot_robot WHERE robot_id=%s FOR UPDATE', (ROBOT_ID,))
row = cursor.fetchone()
if row and row['create_by'] != OWNER:
raise RuntimeError('同名机器人不属于模拟器,未覆盖')
cursor.execute('SELECT * FROM iot_device WHERE robot_id=%s', (ROBOT_ID,))
if any(device['create_by'] != OWNER for device in cursor.fetchall()):
raise RuntimeError('机器人含有非模拟设备,未修改')
insert_new(cursor, 'iot_robot', dict(id=uuid.uuid4().hex, robot_id=ROBOT_ID,
robot_code='SIM-ROBOT-001', robot_name='模拟测试机器人(永久在线)', robot_model='SIMULATED-AGV',
robot_type='GENERIC', archived_status='0', connect_status='0',
create_by=OWNER, update_by=OWNER, remark=DESCRIPTION), ['robot_id'])
cursor.execute("UPDATE iot_robot SET archived_status='0',update_time=NOW() WHERE robot_id=%s AND create_by=%s", (ROBOT_ID, OWNER))
insert_new(cursor, 'iot_device', dict(id=uuid.uuid4().hex, robot_id=ROBOT_ID,
device_id=DEVICE_ID, device_name='模拟AGV底盘(测试设备)', device_kind=1,
device_type='SIMULATED_AGV', device_role='模拟底盘', device_index=0, enabled='1',
online_status='0', has_error='0', manager_state=1, health_status=1,
create_by=OWNER, update_by=OWNER, remark=DESCRIPTION), ['robot_id', 'device_id'])
cursor.execute("UPDATE iot_device SET enabled='1',update_time=NOW() WHERE robot_id=%s AND device_id=%s AND create_by=%s", (ROBOT_ID, DEVICE_ID, OWNER))
cursor.execute('UPDATE iot_robot SET create_time=COALESCE(create_time,NOW()) WHERE robot_id=%s AND create_by=%s', (ROBOT_ID, OWNER))
cursor.execute('UPDATE iot_device SET create_time=COALESCE(create_time,NOW()) WHERE robot_id=%s AND create_by=%s', (ROBOT_ID, OWNER))
self.connection.commit()
def heartbeat(self, port, world):
# The Java resolver compares heartbeat age with the application clock.
# A MySQL server clock more than 15 seconds behind would reject NOW()
# immediately. DATETIME has no zone, so bind the JDBC Asia/Shanghai time.
now = datetime.now(timezone(timedelta(hours=8))).replace(tzinfo=None)
with self.cursor() as cursor:
cursor.execute('SELECT archived_status,create_by FROM iot_robot WHERE robot_id=%s FOR UPDATE', (ROBOT_ID,))
row = cursor.fetchone()
if not row or row['create_by'] != OWNER or row['archived_status'] == '1':
cursor.execute('DELETE FROM iot_device WHERE robot_id=%s AND create_by=%s', (ROBOT_ID, OWNER))
self.connection.commit()
return False
cursor.execute("SELECT id FROM iot_device WHERE robot_id=%s AND device_id=%s AND create_by=%s", (ROBOT_ID, DEVICE_ID, OWNER))
if not cursor.fetchone():
self.connection.rollback()
return False
cursor.execute("UPDATE iot_robot SET connect_status='1',ip_address='127.0.0.1',port=%s,"
"runtime_status=%s,battery_level=100,current_position=%s,last_heartbeat_time=%s,"
"software_version='SIMULATED-v1',update_by=%s,update_time=%s WHERE robot_id=%s AND create_by=%s",
(port, '5' if world.estop else '2', ','.join(str(value) for value in world.pose), now, OWNER, now, ROBOT_ID, OWNER))
cursor.execute("UPDATE iot_device SET online_status='1',has_error='0',health_status=1,"
"last_seen_time=%s,status_updated_time=%s,offline_time=NULL,update_by=%s,update_time=%s "
"WHERE robot_id=%s AND device_id=%s AND create_by=%s", (now, now, OWNER, now, ROBOT_ID, DEVICE_ID, OWNER))
self.connection.commit()
return True
def offline(self):
with self.cursor() as cursor:
cursor.execute("UPDATE iot_robot SET connect_status='0',update_time=NOW() WHERE robot_id=%s AND create_by=%s", (ROBOT_ID, OWNER))
cursor.execute("UPDATE iot_device SET online_status='0',offline_time=NOW() WHERE robot_id=%s AND create_by=%s", (ROBOT_ID, OWNER))
self.connection.commit()
def remove(self):
with self.cursor() as cursor:
cursor.execute('SELECT create_by FROM iot_robot WHERE robot_id=%s FOR UPDATE', (ROBOT_ID,))
row = cursor.fetchone()
if row and row['create_by'] != OWNER:
raise RuntimeError('拒绝删除非模拟机器人')
cursor.execute('SELECT create_by FROM iot_device WHERE robot_id=%s', (ROBOT_ID,))
if any(device['create_by'] != OWNER for device in cursor.fetchall()):
raise RuntimeError('拒绝删除非模拟设备')
for table in ('iot_robot_map', 'iot_robot_terminal'):
cursor.execute('DELETE FROM ' + table + ' WHERE robot_id=%s', (ROBOT_ID,))
cursor.execute('DELETE FROM iot_device WHERE robot_id=%s AND create_by=%s', (ROBOT_ID, OWNER))
cursor.execute('DELETE FROM iot_robot WHERE robot_id=%s AND create_by=%s', (ROBOT_ID, OWNER))
self.connection.commit()
def serve():
settings = read_json(SETTINGS, {})
if not settings.get('enabled'):
return
store = ResourceStore()
with store.cursor() as cursor:
cursor.execute("SELECT GET_LOCK('am-freescan/simulated-edge',0) AS acquired")
if cursor.fetchone()['acquired'] != 1:
raise RuntimeError('模拟器已在运行')
world = SimulatedAgv()
server, port = create_grpc_server(settings['port'], world)
server.start()
try:
while not STOP.exists() and read_json(SETTINGS, {}).get('enabled'):
if not store.heartbeat(port, world):
settings['enabled'] = False
write_json(SETTINGS, settings)
break
write_json(STATUS, dict(owner=OWNER, running=True, pid=os.getpid(), port=port,
robotId=ROBOT_ID, deviceId=DEVICE_ID, lastHeartbeat=time.time(), simulated=True))
for _ in range(30):
if STOP.exists():
break
time.sleep(0.1)
finally:
server.stop(1).wait()
store.offline()
store.connection.close()
write_json(STATUS, dict(owner=OWNER, running=False, pid=os.getpid(), simulated=True))
def probe(port):
try:
import grpc
common, command, service, _ = protocol()
with grpc.insecure_channel('127.0.0.1:' + str(port)) as channel:
result = service.AgvServiceStub(channel).getRuntimeState(command.AgvRuntimeStateCommand.Request(
header=common.CommandHeader.Request(device_id=DEVICE_ID)), timeout=1)
return result.header.success and result.state.last_error.startswith('SIMULATED:')
except Exception:
return False
def start():
settings = read_json(SETTINGS, {})
if not settings.get('enabled'):
raise RuntimeError('模拟器未启用;请先执行 create')
if probe(settings['port']):
return
STOP.unlink(missing_ok=True)
LOCAL.mkdir(parents=True, exist_ok=True)
with (LOCAL / 'server.log').open('ab') as log:
process = subprocess.Popen([sys.executable, '-u', str(Path(__file__).resolve()), 'serve'],
cwd=ROOT, stdout=log, stderr=subprocess.STDOUT,
creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0,
env={**os.environ, 'PYTHONUTF8': '1'})
for _ in range(40):
if probe(settings['port']):
return
if process.poll() is not None:
raise RuntimeError('模拟器启动失败,详情见 .local/simulator/server.log')
time.sleep(0.25)
raise RuntimeError('模拟器启动超时,详情见 .local/simulator/server.log')
def stop():
LOCAL.mkdir(parents=True, exist_ok=True)
STOP.touch()
for _ in range(60):
if not read_json(STATUS, {}).get('running'):
return
time.sleep(0.2)
raise RuntimeError('模拟器尚未停止,未删除任何资源')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=['create', 'start', 'stop', 'remove', 'status', 'serve'])
parser.add_argument('--port', type=int, default=DEFAULT_PORT)
args = parser.parse_args()
if args.action == 'serve':
serve()
return
if args.action == 'create':
if not 1024 <= args.port <= 65535:
raise ValueError('模拟器端口必须在1024到65535之间')
# Compile dependencies before touching persistent resources.
protocol()
settings = read_json(SETTINGS, {})
if settings and settings.get('port') != args.port and probe(settings['port']):
raise RuntimeError('请先停止模拟器再修改端口')
store = ResourceStore()
try:
store.provision()
finally:
store.connection.close()
write_json(SETTINGS, dict(enabled=True, port=args.port, owner=OWNER))
start()
elif args.action == 'start':
start()
elif args.action == 'stop':
stop()
elif args.action == 'remove':
settings = read_json(SETTINGS, {})
settings['enabled'] = False
write_json(SETTINGS, settings)
stop()
store = ResourceStore()
try:
store.remove()
finally:
store.connection.close()
state = read_json(STATUS, {})
print(json.dumps(dict(action=args.action, robotId=ROBOT_ID, deviceId=DEVICE_ID,
enabled=read_json(SETTINGS, {}).get('enabled', False),
running=state.get('running', False), simulated=True), ensure_ascii=False))
if __name__ == '__main__':
main()