StatisticsWorker.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * 统计信息轮询 Worker
  3. * 功能:定时获取 VSLAM 统计信息(关键帧数量、闭环数量、运行状态)
  4. */
  5. // 轮询定时器 ID
  6. let pollingIntervalId = null
  7. /**
  8. * 监听主线程消息
  9. */
  10. self.onmessage = function(event) {
  11. const action = event.data.action
  12. if (action === 'startPolling') {
  13. // 启动轮询
  14. const { url, interval = 1000 } = event.data // 默认 1 秒轮询一次
  15. // 停止现有轮询(防止重复)
  16. if (pollingIntervalId) {
  17. clearInterval(pollingIntervalId)
  18. }
  19. // 立即执行一次
  20. const fetchStatistics = () => {
  21. fetch(url)
  22. .then(response => {
  23. if (!response.ok) {
  24. throw new Error(`HTTP ${response.status}: ${response.statusText}`)
  25. }
  26. return response.json()
  27. })
  28. .then(data => {
  29. // 返回数据到主线程
  30. // 数据格式: { keyframes: 数量, closures: 闭环数, running: true/false }
  31. console.log('[StatisticsWorker] 获取成功:', data)
  32. self.postMessage({ type: 'success', data: data })
  33. })
  34. .catch(error => {
  35. console.error('[StatisticsWorker] 获取失败:', error)
  36. // 将错误发送回主线程
  37. self.postMessage({ type: 'error', error: error.message })
  38. })
  39. }
  40. // 立即执行一次
  41. fetchStatistics()
  42. // 开始定时轮询
  43. pollingIntervalId = setInterval(fetchStatistics, interval)
  44. console.log('[StatisticsWorker] 启动轮询:', url, '间隔:', interval + 'ms')
  45. } else if (action === 'stopPolling') {
  46. // 停止轮询
  47. if (pollingIntervalId) {
  48. clearInterval(pollingIntervalId)
  49. pollingIntervalId = null
  50. }
  51. }
  52. }
  53. /**
  54. * 错误处理
  55. */
  56. self.onerror = function(error) {
  57. console.error('Worker error:', error)
  58. }