加入二维码设置

This commit is contained in:
ywb
2026-05-20 20:02:31 +08:00
parent f05d6ea059
commit 084faad1b2
5 changed files with 738 additions and 325 deletions
+206 -309
View File
@@ -11,7 +11,7 @@ createApp({
sequence: [],
poseForm: { name: '', photo_type: 'front', description: '' },
// 地图
mapForm: { map_dir: '/home/elephant/agv_pro_ros2/install/agv_pro_navigation2/share/agv_pro_navigation2/map/', map_file: 'map.yaml' },
mapForm: { map_dir: '/home/elephant/agv_pro_ros2/src/agv_pro_navigation2/map/', map_file: 'map.yaml' },
mapMsg: '',
mapLoaded: false,
mapImageUrl: '',
@@ -22,8 +22,6 @@ createApp({
nav2Available: false,
// 点位
points: [],
editingPoint: null, // 当前编辑的点位 {pointRow, col}
pointEditor: { x: 0, y: 0, yaw: 0 },
newPointName: '',
newPointMode: 'front',
newPointSequence: ['front', 'back'],
@@ -47,18 +45,31 @@ createApp({
agvMoveInterval: null,
agvCameraUrl: API + '/api/camera/refresh',
agvCameraTimer: null,
// 初始化定位
initPoseLoading: false,
initPoseMsg: '',
initAmclPoseLoading: false,
initAmclPoseMsg: '',
// QR
qrScanning: false,
qrConfigs: [],
qrScanningId: null,
armCameraUrl: API + '/api/camera/arm_refresh',
newQrName: '',
}
},
mounted() {
this.refresh()
this.refreshAngles()
this.loadQrConfigs()
this.nav2Timer = setInterval(this.refreshNavStatus, 3000)
},
computed: {
hasQr() {
return !!(this.selectedMachine && this.selectedMachine.qr)
},
hasQrValue() {
return !!(this.selectedMachine && this.selectedMachine.qr && this.selectedMachine.qr.qr_value)
},
hasQrModelId() {
return !!(this.selectedMachine && this.selectedMachine.qr && this.selectedMachine.qr.model_id)
}
},
watch: {
tab(val) {
if (val === 'agv') {
@@ -135,12 +146,9 @@ createApp({
const res = await fetch(API + '/api/navigate/status')
if (res.ok) {
const data = await res.json()
this.nav2Available = data.nav2_available || false
// API returns "current_position", normalize to our field
const cp = data.current_position || data.current_pos || null
if (cp) {
this.navCurrentPos = cp
console.log('[Setting] nav2:', data.nav2_available, 'cp:', cp.map(function(x){return x.toFixed(2)}), 'mapLoaded:', this.mapLoaded, 'mapMeta:', this.mapMeta ? 'ok' : 'null')
this.nav2Available = data.nav2_available
if (data.current_pos) {
this.navCurrentPos = data.current_pos
}
}
} catch (e) {}
@@ -153,8 +161,6 @@ createApp({
const { resolution, origin } = this.mapMeta
const wx = origin[0] + px * resolution * this.mapMeta.width
const wy = origin[1] + (1 - py) * resolution * this.mapMeta.height
// 确认框
if (!confirm(`确定导航到坐标 (${wx.toFixed(2)}, ${wy.toFixed(2)}) 吗?`)) return
try {
const res = await fetch(API + '/api/navigate/to', {
method: 'POST',
@@ -307,8 +313,6 @@ createApp({
this.missionConfig.rows = data.config.rows || 3
this.missionConfig.cols = data.config.cols || 3
this.missionConfig.grid = data.config.grid || []
this.missionConfig.positions = data.config.positions || []
this.missionConfig.machines = data.config.machines || []
}
} catch (e) { console.error('加载任务配置失败', e) }
},
@@ -353,13 +357,22 @@ createApp({
try {
const res = await fetch(API + '/api/mission/machines')
const data = await res.json()
this.missionConfig.machines = data.machines || []
this.missionConfig.machines = (data.machines || []).map(m => {
if (!m.front) m.front = { coords: [0,0,0], poses: [] }
if (!m.back) m.back = { coords: [0,0,0], poses: [] }
if (!m.qr) m.qr = { coords: [0,0,0], qr_value: '', model_id: '' }
return m
})
} catch (e) { console.error('加载机器列表失败', e) }
},
getMachineAt(ri, ci) {
if (!this.missionConfig.machines) return null
return this.missionConfig.machines.find(m => m.row === ri && m.col === ci) || null
},
getPointAt(ri, ci) {
if (!this.missionConfig.positions) return null
return this.missionConfig.positions.find(p => p.row === ri && p.col === ci) || null
},
getPositionAt(ri, ci) {
if (!this.missionConfig.machines) return null
const machine = this.getMachineAt(ri, ci)
@@ -394,7 +407,8 @@ createApp({
row: ri,
col: ci,
front: { coords: [0, 0, 0], poses: [] },
back: { coords: [0, 0, 0], poses: [] }
back: { coords: [0, 0, 0], poses: [] },
qr: { coords: [0, 0, 0], qr_value: '', model_id: '' }
})
})
const data = await res.json()
@@ -411,6 +425,8 @@ createApp({
else if (!Array.isArray(machine.front.coords)) machine.front.coords = [0, 0, 0]
if (!machine.back) machine.back = { coords: [0, 0, 0], poses: [] }
else if (!Array.isArray(machine.back.coords)) machine.back.coords = [0, 0, 0]
if (!machine.qr) machine.qr = { coords: [0, 0, 0], qr_value: '', model_id: '' }
else if (!Array.isArray(machine.qr.coords)) machine.qr.coords = [0, 0, 0]
this.selectedMachine = machine
},
clearSelection() {
@@ -432,7 +448,8 @@ createApp({
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
front: this.selectedMachine.front,
back: this.selectedMachine.back
back: this.selectedMachine.back,
qr: this.selectedMachine.qr || { coords: [0, 0, 0], qr_value: '', model_id: '' }
})
})
if (res.ok) {
@@ -628,6 +645,174 @@ createApp({
async agvStop() {
await fetch(API + '/api/agv/stop', { method: 'POST' })
},
// === QR 安全访问器(避免 v-model 在 v-if 内因 Vue 编译器优化导致 undefined 报错)===
machineHasQr(m) {
if (!m || !m.qr || !m.qr.coords || m.qr.coords.length < 2) return false
return m.qr.coords[0] !== 0 || m.qr.coords[1] !== 0
},
qrMarkerStyle(m) {
if (!this.machineHasQr(m)) return { display: 'none' }
return { left: this.getMapX(m.qr.coords) + '%', top: this.getMapY(m.qr.coords) + '%' }
},
qrMarkerTitle(m) {
if (!m || !m.qr) return ''
return 'QR: ' + (m.qr.qr_value || '未扫描')
},
safeQr(key) {
if (!this.selectedMachine || !this.selectedMachine.qr) return ''
return this.selectedMachine.qr[key] ?? ''
},
safeQrCoord(idx) {
if (!this.selectedMachine || !this.selectedMachine.qr || !this.selectedMachine.qr.coords) return 0
return this.selectedMachine.qr.coords[idx] !== undefined ? this.selectedMachine.qr.coords[idx] : 0
},
setQrCoord(idx, val) {
if (this.selectedMachine && this.selectedMachine.qr && this.selectedMachine.qr.coords) {
this.selectedMachine.qr.coords[idx] = val
}
},
safeQrModelName() {
if (!this.selectedMachine || !this.selectedMachine.qr || !this.selectedMachine.qr.model_id) return ''
return this.getModelName(this.selectedMachine.qr.model_id)
},
// === QR 二维码 ===
async readQRPosition() {
if (!this.agvConnected) { alert('AGV 未连接'); return }
try {
const res = await fetch(API + '/api/agv/position')
const data = await res.json()
if (data.ok && data.position) {
const [x, y, theta] = data.position
if (!this.selectedMachine.qr) this.selectedMachine.qr = { coords: [0, 0, 0], qr_value: '', model_id: '' }
this.selectedMachine.qr.coords = [x, y, theta]
} else {
alert('读取位置失败: ' + (data.error || '未知错误'))
}
} catch (e) { alert('读取位置失败: ' + e.message) }
},
async scanQRCode(machineId) {
if (!this.cameraOpened) { alert('AGV 摄像头未打开'); return }
this.qrScanning = true
try {
const res = await fetch(API + '/api/mission/qr_scan/' + machineId, { method: 'POST' })
const data = await res.json()
if (data.ok) {
await this.loadAllMachines()
const updated = this.getMachineAt(this.selectedMachine.row, this.selectedMachine.col)
if (updated) this.selectMachine(updated)
let msg = '✅ 扫描成功: ' + data.qr_value
if (data.model_name) msg += ' → 匹配机型: ' + data.model_name
else msg += ' → 未匹配到机型'
alert(msg)
} else {
alert('❌ ' + (data.error || '扫描失败'))
}
} catch (e) { alert('扫描失败: ' + e.message) }
this.qrScanning = false
},
// ========== 二维码配置(独立 Tab==========
async loadQrConfigs() {
try {
const res = await fetch(API + '/api/qr/configs')
const data = await res.json()
this.qrConfigs = (data.configs || []).map(c => {
// 兼容旧版的 coords → 转为 joint_angles
if (!c.joint_angles || !Array.isArray(c.joint_angles)) {
c.joint_angles = [0, 0, 0, 0, 0, 0]
}
return c
})
} catch (e) { console.error('加载二维码配置失败', e) }
},
async addQrConfig() {
const name = this.newQrName.trim() || ''
try {
const res = await fetch(API + '/api/qr/configs', {
method: 'POST', headers: {'Content-Type':'application/json'},
body: JSON.stringify({ name: name || undefined })
})
const data = await res.json()
if (data.ok) {
this.qrConfigs.push(data.entry)
this.newQrName = ''
}
} catch (e) { alert('添加失败: ' + e.message) }
},
getQrAngle(q, idx) {
if (!q || !q.joint_angles || !Array.isArray(q.joint_angles)) return 0
return q.joint_angles[idx] !== undefined ? q.joint_angles[idx] : 0
},
async updateQrAngle(qrId, idx, val) {
const q = this.qrConfigs.find(x => x.id === qrId)
if (!q) return
if (!q.joint_angles || !Array.isArray(q.joint_angles)) q.joint_angles = [0,0,0,0,0,0]
q.joint_angles[idx] = parseFloat(val) || 0
try {
await fetch(API + '/api/qr/configs/' + qrId, {
method: 'PUT', headers: {'Content-Type':'application/json'},
body: JSON.stringify({ joint_angles: q.joint_angles })
})
} catch (e) { console.error('保存角度失败', e) }
},
async readQrAngles(qrId) {
if (!this.armConnected) { alert('机械臂未连接'); return }
try {
const res = await fetch(API + '/api/qr/configs/' + qrId + '/read-angles', { method: 'POST' })
const data = await res.json()
if (data.ok) {
const q = this.qrConfigs.find(x => x.id === qrId)
if (q && data.joint_angles) {
q.joint_angles = data.joint_angles
}
} else {
alert('读取角度失败: ' + (data.error || '未知错误'))
}
} catch (e) { alert('读取角度失败: ' + e.message) }
},
async saveQrConfig(qrId) {
const q = this.qrConfigs.find(x => x.id === qrId)
if (!q) return
try {
const res = await fetch(API + '/api/qr/configs/' + qrId, {
method: 'PUT', headers: {'Content-Type':'application/json'},
body: JSON.stringify({ name: q.name })
})
if (!res.ok) alert('保存名称失败')
} catch (e) { alert('保存失败: ' + e.message) }
},
async deleteQrConfig(qrId) {
if (!confirm('确定删除此二维码点位?')) return
try {
await fetch(API + '/api/qr/configs/' + qrId, { method: 'DELETE' })
this.qrConfigs = this.qrConfigs.filter(x => x.id !== qrId)
} catch (e) { alert('删除失败: ' + e.message) }
},
getQrModelName(modelId) {
const model = this.models.find(m => m.id === modelId)
return model ? model.name : ''
},
getModelName(modelId) {
const model = this.models.find(m => m.id === modelId)
return model ? model.name : ''
},
async scanQrEntry(qrId) {
this.qrScanningId = qrId
try {
const res = await fetch(API + '/api/qr/scan/' + qrId, { method: 'POST' })
const data = await res.json()
if (data.ok) {
await this.loadQrConfigs()
let msg = '扫描成功: ' + data.qr_value
if (data.model_name) msg += ' 匹配机型: ' + data.model_name
else msg += ' 未匹配到机型'
alert(msg)
} else { alert(data.error || '扫描失败') }
} catch (e) { alert('扫描失败: ' + e.message) }
this.qrScanningId = null
},
onArmPreviewError() {
// 机械臂摄像头预览失败,静默处理
},
async agvResetCollision() {
if (!this.agvConnected) {
alert('AGV 未连接')
@@ -648,293 +833,5 @@ createApp({
alert('❌ 复位请求失败: ' + e.message)
}
},
async initPose() {
if (!this.agvConnected) { alert('AGV 未连接'); return }
if (!confirm('确定要将 AMCL 初始位置设为 (0,0,0) 吗?这会重置定位。')) return
this.initPoseLoading = true
this.initPoseMsg = ''
try {
const res = await fetch(API + '/api/mission/init_pose', { method: 'POST' })
const data = await res.json()
if (data.ok) {
this.initPoseMsg = '✅ ' + (data.message || '初始化成功')
} else {
this.initPoseMsg = '❌ ' + (data.error || '初始化失败')
}
} catch (e) {
this.initPoseMsg = '❌ 请求失败: ' + e.message
}
this.initPoseLoading = false
setTimeout(() => { this.initPoseMsg = '' }, 5000)
},
async initAmclPose() {
if (!this.agvConnected) { alert('AGV 未连接'); return }
if (!confirm('确定要将 AMCL 初始位置设为 (0,0,0) 吗?这会重置定位。')) return
this.initAmclPoseLoading = true
this.initAmclPoseMsg = ''
try {
const res = await fetch(API + '/api/mission/init_pose', { method: 'POST' })
const data = await res.json()
if (data.ok) {
this.initAmclPoseMsg = '✅ ' + (data.message || '初始化成功')
} else {
this.initAmclPoseMsg = '❌ ' + (data.error || '初始化失败')
}
} catch (e) {
this.initAmclPoseMsg = '❌ 请求失败: ' + e.message
}
this.initAmclPoseLoading = false
setTimeout(() => { this.initAmclPoseMsg = '' }, 5000)
},
getPointAt(pointRow, col) {
var positions = this.missionConfig.positions || []
// 在独立 positions 数组中查找 (pointRow, col)
for (var i = 0; i < positions.length; i++) {
var p = positions[i]
if (parseInt(p.row) === pointRow && parseInt(p.col) === col) {
// 优先找 shoot,其次找 front/back
if (p.side === 'shoot') return p
// 再看有没有同一(row,col)的shoot
}
}
// 再找同(row,col)的shoot类型
for (var i = 0; i < positions.length; i++) {
var p = positions[i]
if (parseInt(p.row) === pointRow && parseInt(p.col) === col && p.side === 'shoot') {
return p
}
}
// 兼容旧数据:尝试从机器对象的 front/back 获取
var machineAbove = this.getMachineAt(pointRow - 1, col) // 上面的机器
var machineBelow = this.getMachineAt(pointRow, col) // 下面的机器
if (pointRow === 0 && machineBelow) {
// 第一个点位行 → 下面机器的正面
return machineBelow.front || { coords: [0, 0, 0], poses: [] }
}
if (pointRow === this.missionConfig.rows && machineAbove) {
// 最后一个点位行 → 上面机器的背面
return machineAbove.back || { coords: [0, 0, 0], poses: [] }
}
// 中间点位行:优先返回上面机器的背面
if (machineAbove && machineAbove.back) {
return machineAbove.back
}
if (machineBelow && machineBelow.front) {
return machineBelow.front
}
return null
},
// 点位归属标签
getPointOwnerLabel(pointRow, col) {
var rows = this.missionConfig.rows
var labels = []
if (pointRow === 0) {
var m = this.getMachineAt(0, col)
if (m) labels.push('机器' + (m.row + 1) + '正面')
} else if (pointRow === rows) {
var m2 = this.getMachineAt(rows - 1, col)
if (m2) labels.push('机器' + (m2.row + 1) + '背面')
} else {
var mAbove = this.getMachineAt(pointRow - 1, col)
var mBelow = this.getMachineAt(pointRow, col)
if (mAbove) labels.push('机器' + (mAbove.row + 1) + '背面')
if (mBelow) labels.push('机器' + (mBelow.row + 1) + '正面')
}
if (labels.length === 0) return '第' + (col + 1) + '列 · 无归属'
return '第' + (col + 1) + '列 · ' + labels.join('/')
},
canClearPoint(pointRow, col) {
var rows = this.missionConfig.rows
if (pointRow > 0 && pointRow <= rows) {
var mAbove = this.getMachineAt(pointRow - 1, col)
if (mAbove) return false
}
if (pointRow >= 0 && pointRow < rows) {
var mBelow = this.getMachineAt(pointRow, col)
if (mBelow) return false
}
return true
},
openPointEdit(pointRow, col) {
var existing = this.getPointAt(pointRow, col)
if (existing && existing.coords) {
this.pointEditor.x = existing.coords[0] !== undefined ? existing.coords[0] : 0
this.pointEditor.y = existing.coords[1] !== undefined ? existing.coords[1] : 0
this.pointEditor.yaw = existing.coords[2] !== undefined ? existing.coords[2] : 0
} else {
this.pointEditor.x = 0
this.pointEditor.y = 0
this.pointEditor.yaw = 0
}
this.editingPoint = { pointRow: pointRow, col: col }
},
closePointEdit() {
this.editingPoint = null
},
async loadPointFromAgv() {
if (!this.agvConnected) { alert('请先连接AGV'); return }
try {
const res = await fetch(API + '/api/agv/position')
const pos = await res.json()
if (pos.ok && pos.position && Array.isArray(pos.position)) {
this.pointEditor.x = pos.position[0] ?? 0
this.pointEditor.y = pos.position[1] ?? 0
this.pointEditor.yaw = pos.position[2] ?? 0
alert('✅ 已读取AGV位置: (' + this.pointEditor.x.toFixed(2) + ', ' + this.pointEditor.y.toFixed(2) + ', ' + this.pointEditor.yaw.toFixed(2) + ')')
} else if (pos.ok && (!pos.position || !Array.isArray(pos.position))) {
alert('⚠️ AGV 未发布位置数据,请检查 AGV 传感器是否正常')
} else {
alert('读取AGV位置失败: ' + (pos.error || '未知错误'))
}
} catch (e) { alert('读取AGV位置失败: ' + e.message) }
},
async savePoint() {
if (!this.editingPoint) return
var pointRow = this.editingPoint.pointRow
var col = this.editingPoint.col
var coords = [this.pointEditor.x, this.pointEditor.y, this.pointEditor.yaw]
try {
var saveRes = await fetch(API + '/api/mission/positions', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
row: pointRow, col: col, side: 'shoot', coords: coords, poses: []
})
})
var saveData = await saveRes.json()
if (!saveData.ok) { alert('保存点位失败: ' + (saveData.error || '未知错误')); return }
this.syncPointToMachines(pointRow, col, coords)
await this.loadMissionConfig()
alert('✅ 点位坐标已保存: (' + coords[0].toFixed(2) + ', ' + coords[1].toFixed(2) + ', ' + coords[2].toFixed(2) + ')')
this.closePointEdit()
} catch (e) { alert('保存点位失败: ' + e.message) }
},
syncPointToMachines(pointRow, col, coords) {
var rows = this.missionConfig.rows
if (pointRow === 0) {
var m0 = this.getMachineAt(0, col)
if (m0) this.updateMachineSide(m0, 'front', coords)
return
}
if (pointRow === rows) {
var mLast = this.getMachineAt(rows - 1, col)
if (mLast) this.updateMachineSide(mLast, 'back', coords)
return
}
var mAbove = this.getMachineAt(pointRow - 1, col)
var mBelow = this.getMachineAt(pointRow, col)
if (mAbove) this.updateMachineSide(mAbove, 'back', coords)
if (mBelow) this.updateMachineSide(mBelow, 'front', coords)
},
async updateMachineSide(machine, side, coords) {
try {
var update = {}
update[side] = { coords: coords, poses: (machine[side] && machine[side].poses) ? machine[side].poses : [] }
await fetch(API + '/api/mission/machines/' + machine.id, {
method: 'PUT', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(update)
})
} catch (e) { console.error('同步机器坐标失败', e) }
},
async clearPoint() {
if (!this.editingPoint) return
var pointRow = this.editingPoint.pointRow
var col = this.editingPoint.col
if (!this.canClearPoint(pointRow, col)) {
var ownerLabel = this.getPointOwnerLabel(pointRow, col)
alert('⚠️ 无法清空!此点位服务于: ' + ownerLabel + '\n必须先移除相关机器才能清空此点位。')
return
}
if (!confirm('确定清空此点位坐标?')) return
try {
await fetch(API + '/api/mission/positions/' + pointRow + '/' + col, { method: 'DELETE' })
await this.loadMissionConfig()
alert('✅ 点位已清空')
this.closePointEdit()
} catch (e) { alert('清空点位失败: ' + e.message) }
},
async navigateToPoint() {
if (!this.editingPoint || !this.pointEditor) return
var coords = [this.pointEditor.x, this.pointEditor.y, this.pointEditor.yaw]
if (!confirm('确定导航到点位 (' + coords[0].toFixed(2) + ', ' + coords[1].toFixed(2) + ') 吗?')) return
try {
var res = await fetch(API + '/api/navigate/to', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ x: coords[0], y: coords[1], yaw: coords[2] })
})
var data = await res.json()
if (data.ok) {
alert('✅ 导航已启动')
} else {
alert('❌ ' + (data.error || '导航启动失败'))
}
} catch (e) { alert('导航请求失败: ' + e.message) }
},
async refreshPoseAngles(modelId, poseId) {
if (!this.armConnected) { alert('机械臂未连接'); return }
try {
var res = await fetch(API + '/api/arm/get_angles')
var data = await res.json()
if (data.ok && data.angles) {
var model = this.models.find(m => m.id === modelId)
if (model) {
var pose = model.poses.find(p => p.id === poseId)
if (pose) {
pose.arm_angles = [...data.angles]
await fetch(API + '/api/models/' + modelId + '/poses/' + poseId, {
method: 'PUT', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ arm_angles: pose.arm_angles })
})
}
}
}
} catch (e) { console.error('refreshPoseAngles error:', e) }
},
async applyPoseAngles(modelId, poseId) {
var model = this.models.find(m => m.id === modelId)
if (model) {
var pose = model.poses.find(p => p.id === poseId)
if (pose && pose.arm_angles) {
try {
await fetch(API + '/api/arm/set_angles', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ angles: pose.arm_angles, speed: 500 })
})
} catch (e) { console.error('applyPoseAngles error:', e) }
}
}
},
async adjustPoseAngle(modelId, poseId, jointIndex, delta) {
var model = this.models.find(m => m.id === modelId)
if (model) {
var pose = model.poses.find(p => p.id === poseId)
if (pose) {
if (!pose.arm_angles) pose.arm_angles = [0, 0, 0, 0, 0, 0]
pose.arm_angles[jointIndex] = (pose.arm_angles[jointIndex] || 0) + delta
await fetch(API + '/api/models/' + modelId + '/poses/' + poseId, {
method: 'PUT', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ arm_angles: pose.arm_angles })
})
await fetch(API + '/api/arm/set_angle', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ joint: 'J' + (jointIndex + 1), angle: pose.arm_angles[jointIndex] })
})
}
}
},
}
}).mount('#app')