simulator.js 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718
  1. (function () {
  2. const DEFAULT_CENTER = [31.2304, 121.4737]
  3. const DEFAULT_CONFIG_URL = 'https://oss-mbh5.colormaprun.com/wxmini/test/game.json'
  4. const DEFAULT_TILE_URL = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
  5. const PROXY_BASE_URL = `${location.origin}/proxy?url=`
  6. const WS_URL = `ws://${location.hostname}:17865/mock-gps`
  7. const DEFAULT_GATEWAY_BRIDGE_URL = 'ws://127.0.0.1:18080/ws'
  8. const LEGACY_GATEWAY_BRIDGE_URLS = new Set([
  9. 'ws://127.0.0.1:8080/ws',
  10. 'ws://localhost:8080/ws',
  11. ])
  12. const BRIDGE_CONFIG_STORAGE_KEY = 'mock-gps-sim.bridge-config'
  13. const BRIDGE_PRESETS_STORAGE_KEY = 'mock-gps-sim.bridge-presets'
  14. const map = L.map('map').setView(DEFAULT_CENTER, 16)
  15. let tileLayer = createTileLayer(DEFAULT_TILE_URL, {
  16. maxZoom: 20,
  17. attribution: '© OpenStreetMap',
  18. }).addTo(map)
  19. const liveMarker = L.circleMarker(DEFAULT_CENTER, {
  20. radius: 11,
  21. color: '#ffffff',
  22. weight: 3,
  23. fillColor: '#ff2f92',
  24. fillOpacity: 0.94,
  25. }).addTo(map)
  26. const pathLine = L.polyline([], {
  27. color: '#0ea5a4',
  28. weight: 4,
  29. opacity: 0.9,
  30. }).addTo(map)
  31. const courseLayer = L.layerGroup().addTo(map)
  32. const pathMarkers = []
  33. const pathPoints = []
  34. const state = {
  35. socket: null,
  36. connected: false,
  37. socketConnecting: false,
  38. streaming: false,
  39. heartRateStreaming: false,
  40. heartRateSampleMode: false,
  41. pathEditMode: false,
  42. playbackRunning: false,
  43. playbackTimer: 0,
  44. streamTimer: 0,
  45. heartRateStreamTimer: 0,
  46. lastSentText: '--',
  47. lastHeartRateSentText: '--',
  48. lastResourceDetailText: '尚未载入资源',
  49. lastTrackSourceText: '路径待命',
  50. currentLatLng: L.latLng(DEFAULT_CENTER[0], DEFAULT_CENTER[1]),
  51. headingDeg: 0,
  52. currentSegmentIndex: 0,
  53. currentSegmentProgress: 0,
  54. lastPlaybackAt: 0,
  55. heartRateSampleStartedAt: 0,
  56. loadedCourse: null,
  57. resourceLoading: false,
  58. bridgeEnabled: false,
  59. bridgeConnected: false,
  60. bridgeAuthenticated: false,
  61. bridgeTargetText: '--',
  62. bridgeLastStatusText: '--',
  63. bridgeConfigSaving: false,
  64. bridgePresets: [],
  65. }
  66. const elements = {
  67. socketStatus: document.getElementById('socketStatus'),
  68. configUrlInput: document.getElementById('configUrlInput'),
  69. loadConfigBtn: document.getElementById('loadConfigBtn'),
  70. fitCourseBtn: document.getElementById('fitCourseBtn'),
  71. tileUrlInput: document.getElementById('tileUrlInput'),
  72. applyTilesBtn: document.getElementById('applyTilesBtn'),
  73. resetTilesBtn: document.getElementById('resetTilesBtn'),
  74. courseUrlInput: document.getElementById('courseUrlInput'),
  75. loadCourseBtn: document.getElementById('loadCourseBtn'),
  76. clearCourseBtn: document.getElementById('clearCourseBtn'),
  77. resourceStatus: document.getElementById('resourceStatus'),
  78. resourceDetail: document.getElementById('resourceDetail'),
  79. courseJumpList: document.getElementById('courseJumpList'),
  80. realtimeStatus: document.getElementById('realtimeStatus'),
  81. lastSendStatus: document.getElementById('lastSendStatus'),
  82. gatewayBridgeStatus: document.getElementById('gatewayBridgeStatus'),
  83. gatewayBridgeTarget: document.getElementById('gatewayBridgeTarget'),
  84. gatewayBridgeLast: document.getElementById('gatewayBridgeLast'),
  85. gatewayBridgePresetSelect: document.getElementById('gatewayBridgePresetSelect'),
  86. gatewayBridgePresetNameInput: document.getElementById('gatewayBridgePresetNameInput'),
  87. applyGatewayBridgePresetBtn: document.getElementById('applyGatewayBridgePresetBtn'),
  88. saveGatewayBridgePresetBtn: document.getElementById('saveGatewayBridgePresetBtn'),
  89. deleteGatewayBridgePresetBtn: document.getElementById('deleteGatewayBridgePresetBtn'),
  90. gatewayBridgeEnabledInput: document.getElementById('gatewayBridgeEnabledInput'),
  91. gatewayBridgeUrlInput: document.getElementById('gatewayBridgeUrlInput'),
  92. gatewayBridgeTokenInput: document.getElementById('gatewayBridgeTokenInput'),
  93. gatewayBridgeChannelIdInput: document.getElementById('gatewayBridgeChannelIdInput'),
  94. gatewayBridgeDeviceIdInput: document.getElementById('gatewayBridgeDeviceIdInput'),
  95. gatewayBridgeGroupIdInput: document.getElementById('gatewayBridgeGroupIdInput'),
  96. gatewayBridgeSourceIdInput: document.getElementById('gatewayBridgeSourceIdInput'),
  97. gatewayBridgeSourceModeInput: document.getElementById('gatewayBridgeSourceModeInput'),
  98. applyGatewayBridgeConfigBtn: document.getElementById('applyGatewayBridgeConfigBtn'),
  99. reloadGatewayBridgeConfigBtn: document.getElementById('reloadGatewayBridgeConfigBtn'),
  100. playbackStatus: document.getElementById('playbackStatus'),
  101. heartRateStatus: document.getElementById('heartRateStatus'),
  102. lastHeartRateStatus: document.getElementById('lastHeartRateStatus'),
  103. sendHeartRateOnceBtn: document.getElementById('sendHeartRateOnceBtn'),
  104. startHeartRateStreamBtn: document.getElementById('startHeartRateStreamBtn'),
  105. stopHeartRateStreamBtn: document.getElementById('stopHeartRateStreamBtn'),
  106. applyHeartRatePresetBtn: document.getElementById('applyHeartRatePresetBtn'),
  107. toggleHeartRateSampleBtn: document.getElementById('toggleHeartRateSampleBtn'),
  108. heartRateInput: document.getElementById('heartRateInput'),
  109. heartRateHzSelect: document.getElementById('heartRateHzSelect'),
  110. heartRateSampleTemplateSelect: document.getElementById('heartRateSampleTemplateSelect'),
  111. trackFileInput: document.getElementById('trackFileInput'),
  112. importTrackBtn: document.getElementById('importTrackBtn'),
  113. connectBtn: document.getElementById('connectBtn'),
  114. sendOnceBtn: document.getElementById('sendOnceBtn'),
  115. streamBtn: document.getElementById('streamBtn'),
  116. stopStreamBtn: document.getElementById('stopStreamBtn'),
  117. togglePathModeBtn: document.getElementById('togglePathModeBtn'),
  118. clearPathBtn: document.getElementById('clearPathBtn'),
  119. fitPathBtn: document.getElementById('fitPathBtn'),
  120. playPathBtn: document.getElementById('playPathBtn'),
  121. pausePathBtn: document.getElementById('pausePathBtn'),
  122. hzSelect: document.getElementById('hzSelect'),
  123. accuracyInput: document.getElementById('accuracyInput'),
  124. speedInput: document.getElementById('speedInput'),
  125. loopPathInput: document.getElementById('loopPathInput'),
  126. pathHint: document.getElementById('pathHint'),
  127. latText: document.getElementById('latText'),
  128. lonText: document.getElementById('lonText'),
  129. headingText: document.getElementById('headingText'),
  130. pathCountText: document.getElementById('pathCountText'),
  131. log: document.getElementById('log'),
  132. }
  133. elements.configUrlInput.value = DEFAULT_CONFIG_URL
  134. function createTileLayer(urlTemplate, extraOptions) {
  135. return L.tileLayer(urlTemplate, Object.assign({
  136. maxZoom: 20,
  137. attribution: 'Custom Map',
  138. }, extraOptions || {}))
  139. }
  140. function log(message) {
  141. const time = new Date().toLocaleTimeString()
  142. elements.log.textContent = `[${time}] ${message}\n` + elements.log.textContent
  143. }
  144. function setResourceStatus(message, tone) {
  145. elements.resourceStatus.textContent = message
  146. elements.resourceStatus.className = 'hint'
  147. if (tone === 'ok') {
  148. elements.resourceStatus.classList.add('hint--ok')
  149. } else if (tone === 'warn') {
  150. elements.resourceStatus.classList.add('hint--warn')
  151. }
  152. }
  153. function updateReadout() {
  154. elements.latText.textContent = state.currentLatLng.lat.toFixed(6)
  155. elements.lonText.textContent = state.currentLatLng.lng.toFixed(6)
  156. elements.headingText.textContent = `${Math.round(state.headingDeg)}°`
  157. elements.pathCountText.textContent = String(pathPoints.length)
  158. liveMarker.setLatLng(state.currentLatLng)
  159. }
  160. function setSocketBadge(connected) {
  161. elements.socketStatus.textContent = connected ? '已连接' : '未连接'
  162. elements.socketStatus.className = connected ? 'badge badge--ok' : 'badge badge--muted'
  163. }
  164. function formatClockTime(timestamp) {
  165. if (!timestamp) {
  166. return '--'
  167. }
  168. return new Date(timestamp).toLocaleTimeString()
  169. }
  170. function updateUiState() {
  171. elements.connectBtn.textContent = state.connected ? '桥接已连接' : state.socketConnecting ? '连接中...' : '连接桥接'
  172. elements.connectBtn.classList.toggle('is-active', state.connected)
  173. elements.connectBtn.disabled = state.connected || state.socketConnecting
  174. elements.sendOnceBtn.disabled = !state.connected
  175. elements.streamBtn.textContent = state.streaming ? '发送中' : '开始连续发送'
  176. elements.streamBtn.classList.toggle('is-active', state.streaming)
  177. elements.streamBtn.disabled = !state.connected || state.streaming
  178. elements.stopStreamBtn.disabled = !state.streaming
  179. elements.sendHeartRateOnceBtn.disabled = !state.connected
  180. elements.startHeartRateStreamBtn.textContent = state.heartRateStreaming ? '发送中' : '开始连续发送'
  181. elements.startHeartRateStreamBtn.classList.toggle('is-active', state.heartRateStreaming)
  182. elements.startHeartRateStreamBtn.disabled = !state.connected || state.heartRateStreaming
  183. elements.stopHeartRateStreamBtn.disabled = !state.heartRateStreaming
  184. elements.toggleHeartRateSampleBtn.textContent = state.heartRateSampleMode ? '关闭真实样本' : '模拟真实样本'
  185. elements.toggleHeartRateSampleBtn.classList.toggle('is-active', state.heartRateSampleMode)
  186. elements.togglePathModeBtn.textContent = state.pathEditMode ? '关闭路径编辑' : '开启路径编辑'
  187. elements.togglePathModeBtn.classList.toggle('is-active', state.pathEditMode)
  188. elements.importTrackBtn.disabled = state.resourceLoading
  189. elements.clearPathBtn.textContent = pathPoints.length ? `清空路径 (${pathPoints.length})` : '清空路径'
  190. elements.clearPathBtn.disabled = pathPoints.length === 0
  191. elements.fitPathBtn.disabled = pathPoints.length < 2
  192. elements.playPathBtn.textContent = state.playbackRunning ? '回放中' : '开始回放'
  193. elements.playPathBtn.classList.toggle('is-active', state.playbackRunning)
  194. elements.playPathBtn.disabled = pathPoints.length < 2 || state.playbackRunning
  195. elements.pausePathBtn.disabled = !state.playbackRunning
  196. elements.fitCourseBtn.disabled = !state.loadedCourse
  197. elements.clearCourseBtn.disabled = !state.loadedCourse
  198. elements.loadConfigBtn.textContent = state.resourceLoading ? '载入中...' : '载入配置'
  199. elements.loadConfigBtn.disabled = state.resourceLoading
  200. elements.loadCourseBtn.textContent = state.resourceLoading ? '载入中...' : '载入控制点'
  201. elements.loadCourseBtn.disabled = state.resourceLoading
  202. elements.applyTilesBtn.disabled = state.resourceLoading
  203. elements.resetTilesBtn.disabled = state.resourceLoading
  204. elements.lastSendStatus.textContent = `最近发送: ${state.lastSentText}`
  205. elements.lastHeartRateStatus.textContent = `最近发送: ${state.lastHeartRateSentText}`
  206. elements.resourceDetail.textContent = state.lastResourceDetailText
  207. elements.gatewayBridgeTarget.textContent = `目标设备: ${state.bridgeTargetText}`
  208. elements.gatewayBridgeLast.textContent = `最近状态: ${state.bridgeLastStatusText}`
  209. elements.applyGatewayBridgeConfigBtn.disabled = state.bridgeConfigSaving
  210. elements.reloadGatewayBridgeConfigBtn.disabled = state.bridgeConfigSaving
  211. elements.applyGatewayBridgePresetBtn.disabled = state.bridgeConfigSaving || !elements.gatewayBridgePresetSelect.value
  212. elements.saveGatewayBridgePresetBtn.disabled = state.bridgeConfigSaving
  213. elements.deleteGatewayBridgePresetBtn.disabled = state.bridgeConfigSaving || !elements.gatewayBridgePresetSelect.value
  214. if (!state.bridgeEnabled) {
  215. elements.gatewayBridgeStatus.textContent = '未启用'
  216. } else if (state.bridgeConnected && state.bridgeAuthenticated) {
  217. elements.gatewayBridgeStatus.textContent = '已连接并已认证'
  218. } else if (state.bridgeConnected) {
  219. elements.gatewayBridgeStatus.textContent = '已连接,等待认证'
  220. } else {
  221. elements.gatewayBridgeStatus.textContent = '已启用,未连接'
  222. }
  223. if (state.connected && state.streaming) {
  224. elements.realtimeStatus.textContent = `桥接已连接,正在以 ${elements.hzSelect.value} Hz 连续发送`
  225. } else if (state.connected) {
  226. elements.realtimeStatus.textContent = '桥接已连接,待命中'
  227. } else if (state.socketConnecting) {
  228. elements.realtimeStatus.textContent = '桥接连接中'
  229. } else {
  230. elements.realtimeStatus.textContent = '桥接未连接'
  231. }
  232. if (state.connected && state.heartRateStreaming) {
  233. elements.heartRateStatus.textContent = state.heartRateSampleMode
  234. ? `桥接已连接,正在以 ${elements.heartRateHzSelect.value} Hz 发送真实心率样本`
  235. : `桥接已连接,正在以 ${elements.heartRateHzSelect.value} Hz 连续发送心率`
  236. } else if (state.connected) {
  237. elements.heartRateStatus.textContent = state.heartRateSampleMode ? '真实心率样本待命' : '心率模拟待命'
  238. } else if (state.socketConnecting) {
  239. elements.heartRateStatus.textContent = '桥接连接中'
  240. } else {
  241. elements.heartRateStatus.textContent = '桥接未连接'
  242. }
  243. if (state.playbackRunning) {
  244. elements.playbackStatus.textContent = `路径回放中,速度 ${elements.speedInput.value} km/h`
  245. } else if (state.pathEditMode) {
  246. elements.playbackStatus.textContent = '路径编辑中,点击地图追加路径点'
  247. } else if (pathPoints.length >= 2) {
  248. elements.playbackStatus.textContent = `${state.lastTrackSourceText},共 ${pathPoints.length} 个路径点`
  249. } else {
  250. elements.playbackStatus.textContent = '路径待命'
  251. }
  252. }
  253. function bridgeConfigFromServerPayload(payload) {
  254. const config = payload && payload.config ? payload.config : {}
  255. return {
  256. enabled: Boolean(config.enabled),
  257. url: normalizeGatewayBridgeUrl(typeof config.url === 'string' ? config.url : ''),
  258. token: typeof config.token === 'string' ? config.token : '',
  259. channelId: typeof config.channelId === 'string' ? config.channelId : '',
  260. deviceId: typeof config.deviceId === 'string' ? config.deviceId : '',
  261. groupId: typeof config.groupId === 'string' ? config.groupId : '',
  262. sourceId: typeof config.sourceId === 'string' ? config.sourceId : '',
  263. sourceMode: typeof config.sourceMode === 'string' ? config.sourceMode : 'mock',
  264. }
  265. }
  266. function normalizeGatewayBridgeUrl(value) {
  267. const next = String(value || '').trim()
  268. if (!next) {
  269. return DEFAULT_GATEWAY_BRIDGE_URL
  270. }
  271. if (LEGACY_GATEWAY_BRIDGE_URLS.has(next)) {
  272. return DEFAULT_GATEWAY_BRIDGE_URL
  273. }
  274. return next
  275. }
  276. function getBridgeConfigDraft() {
  277. try {
  278. const raw = window.localStorage.getItem(BRIDGE_CONFIG_STORAGE_KEY)
  279. if (!raw) {
  280. return null
  281. }
  282. const parsed = JSON.parse(raw)
  283. return {
  284. enabled: Boolean(parsed.enabled),
  285. url: normalizeGatewayBridgeUrl(typeof parsed.url === 'string' ? parsed.url : ''),
  286. token: typeof parsed.token === 'string' ? parsed.token : '',
  287. channelId: typeof parsed.channelId === 'string' ? parsed.channelId : '',
  288. deviceId: typeof parsed.deviceId === 'string' ? parsed.deviceId : '',
  289. groupId: typeof parsed.groupId === 'string' ? parsed.groupId : '',
  290. sourceId: typeof parsed.sourceId === 'string' ? parsed.sourceId : '',
  291. sourceMode: typeof parsed.sourceMode === 'string' ? parsed.sourceMode : 'mock',
  292. }
  293. } catch (_error) {
  294. return null
  295. }
  296. }
  297. function loadBridgePresets() {
  298. try {
  299. const raw = window.localStorage.getItem(BRIDGE_PRESETS_STORAGE_KEY)
  300. if (!raw) {
  301. return []
  302. }
  303. const parsed = JSON.parse(raw)
  304. if (!Array.isArray(parsed)) {
  305. return []
  306. }
  307. return parsed
  308. .map((item) => {
  309. const config = item && item.config ? item.config : {}
  310. return {
  311. name: item && typeof item.name === 'string' ? item.name.trim() : '',
  312. config: {
  313. enabled: Boolean(config.enabled),
  314. url: normalizeGatewayBridgeUrl(typeof config.url === 'string' ? config.url : ''),
  315. token: typeof config.token === 'string' ? config.token : '',
  316. channelId: typeof config.channelId === 'string' ? config.channelId : '',
  317. deviceId: typeof config.deviceId === 'string' ? config.deviceId : '',
  318. groupId: typeof config.groupId === 'string' ? config.groupId : '',
  319. sourceId: typeof config.sourceId === 'string' ? config.sourceId : '',
  320. sourceMode: typeof config.sourceMode === 'string' ? config.sourceMode : 'mock',
  321. },
  322. }
  323. })
  324. .filter((item) => item.name)
  325. } catch (_error) {
  326. return []
  327. }
  328. }
  329. function saveBridgePresets() {
  330. try {
  331. window.localStorage.setItem(BRIDGE_PRESETS_STORAGE_KEY, JSON.stringify(state.bridgePresets))
  332. } catch (_error) {
  333. // noop
  334. }
  335. }
  336. function renderBridgePresetOptions(selectedName) {
  337. const currentValue = typeof selectedName === 'string'
  338. ? selectedName
  339. : elements.gatewayBridgePresetSelect.value
  340. elements.gatewayBridgePresetSelect.innerHTML = '<option value="">选择预设</option>'
  341. state.bridgePresets.forEach((preset) => {
  342. const option = document.createElement('option')
  343. option.value = preset.name
  344. option.textContent = preset.name
  345. if (preset.name === currentValue) {
  346. option.selected = true
  347. }
  348. elements.gatewayBridgePresetSelect.appendChild(option)
  349. })
  350. }
  351. function saveBridgeConfigDraft(config) {
  352. try {
  353. window.localStorage.setItem(BRIDGE_CONFIG_STORAGE_KEY, JSON.stringify({
  354. ...config,
  355. url: normalizeGatewayBridgeUrl(config && config.url),
  356. }))
  357. } catch (_error) {
  358. // noop
  359. }
  360. }
  361. function fillBridgeConfigForm(config) {
  362. elements.gatewayBridgeEnabledInput.checked = Boolean(config.enabled)
  363. elements.gatewayBridgeUrlInput.value = normalizeGatewayBridgeUrl(config && config.url)
  364. elements.gatewayBridgeTokenInput.value = config.token || ''
  365. elements.gatewayBridgeChannelIdInput.value = config.channelId || ''
  366. elements.gatewayBridgeDeviceIdInput.value = config.deviceId || ''
  367. elements.gatewayBridgeGroupIdInput.value = config.groupId || ''
  368. elements.gatewayBridgeSourceIdInput.value = config.sourceId || ''
  369. elements.gatewayBridgeSourceModeInput.value = config.sourceMode || 'mock'
  370. }
  371. function readBridgeConfigForm() {
  372. return {
  373. enabled: elements.gatewayBridgeEnabledInput.checked,
  374. url: normalizeGatewayBridgeUrl(elements.gatewayBridgeUrlInput.value),
  375. token: String(elements.gatewayBridgeTokenInput.value || '').trim(),
  376. channelId: String(elements.gatewayBridgeChannelIdInput.value || '').trim(),
  377. deviceId: String(elements.gatewayBridgeDeviceIdInput.value || '').trim(),
  378. groupId: String(elements.gatewayBridgeGroupIdInput.value || '').trim(),
  379. sourceId: String(elements.gatewayBridgeSourceIdInput.value || '').trim(),
  380. sourceMode: String(elements.gatewayBridgeSourceModeInput.value || '').trim() || 'mock',
  381. }
  382. }
  383. function selectedBridgePreset() {
  384. const name = String(elements.gatewayBridgePresetSelect.value || '').trim()
  385. if (!name) {
  386. return null
  387. }
  388. return state.bridgePresets.find((item) => item.name === name) || null
  389. }
  390. function applyBridgePresetToForm() {
  391. const preset = selectedBridgePreset()
  392. if (!preset) {
  393. log('未选择桥接预设')
  394. return
  395. }
  396. fillBridgeConfigForm(preset.config)
  397. elements.gatewayBridgePresetNameInput.value = preset.name
  398. saveBridgeConfigDraft(preset.config)
  399. updateUiState()
  400. log(`已载入桥接预设: ${preset.name}`)
  401. }
  402. function saveCurrentBridgePreset() {
  403. const name = String(elements.gatewayBridgePresetNameInput.value || '').trim()
  404. if (!name) {
  405. log('请先输入预设名称')
  406. return
  407. }
  408. const config = readBridgeConfigForm()
  409. const nextPreset = { name, config }
  410. const existingIndex = state.bridgePresets.findIndex((item) => item.name === name)
  411. if (existingIndex >= 0) {
  412. state.bridgePresets.splice(existingIndex, 1, nextPreset)
  413. } else {
  414. state.bridgePresets.push(nextPreset)
  415. state.bridgePresets.sort((left, right) => left.name.localeCompare(right.name, 'zh-CN'))
  416. }
  417. saveBridgePresets()
  418. renderBridgePresetOptions(name)
  419. log(`已保存桥接预设: ${name}`)
  420. updateUiState()
  421. }
  422. function deleteSelectedBridgePreset() {
  423. const preset = selectedBridgePreset()
  424. if (!preset) {
  425. log('未选择桥接预设')
  426. return
  427. }
  428. state.bridgePresets = state.bridgePresets.filter((item) => item.name !== preset.name)
  429. saveBridgePresets()
  430. renderBridgePresetOptions('')
  431. if (elements.gatewayBridgePresetNameInput.value.trim() === preset.name) {
  432. elements.gatewayBridgePresetNameInput.value = ''
  433. }
  434. log(`已删除桥接预设: ${preset.name}`)
  435. updateUiState()
  436. }
  437. function connectSocket() {
  438. if (state.socket && (state.socket.readyState === WebSocket.OPEN || state.socket.readyState === WebSocket.CONNECTING)) {
  439. return
  440. }
  441. const socket = new WebSocket(WS_URL)
  442. state.socket = socket
  443. state.socketConnecting = true
  444. setSocketBadge(false)
  445. updateUiState()
  446. log(`连接 ${WS_URL}`)
  447. socket.addEventListener('open', () => {
  448. state.connected = true
  449. state.socketConnecting = false
  450. setSocketBadge(true)
  451. updateUiState()
  452. log('桥接已连接')
  453. })
  454. socket.addEventListener('close', () => {
  455. state.connected = false
  456. state.socketConnecting = false
  457. stopStream()
  458. stopHeartRateStream()
  459. setSocketBadge(false)
  460. updateUiState()
  461. log('桥接已断开')
  462. })
  463. socket.addEventListener('error', () => {
  464. state.connected = false
  465. state.socketConnecting = false
  466. stopStream()
  467. stopHeartRateStream()
  468. setSocketBadge(false)
  469. updateUiState()
  470. log('桥接连接失败')
  471. })
  472. }
  473. async function refreshGatewayBridgeStatus() {
  474. try {
  475. const response = await fetch('/bridge-status', {
  476. cache: 'no-store',
  477. })
  478. if (!response.ok) {
  479. throw new Error(`HTTP ${response.status}`)
  480. }
  481. const status = await response.json()
  482. state.bridgeEnabled = Boolean(status.enabled)
  483. state.bridgeConnected = Boolean(status.connected)
  484. state.bridgeAuthenticated = Boolean(status.authenticated)
  485. if (status.channelId) {
  486. state.bridgeTargetText = `${status.channelId}${status.deviceId ? ` / ${status.deviceId}` : ''}${status.groupId ? ` / ${status.groupId}` : ''}`
  487. } else {
  488. state.bridgeTargetText = status.deviceId
  489. ? `${status.deviceId}${status.groupId ? ` / ${status.groupId}` : ''}`
  490. : '--'
  491. }
  492. state.bridgeLastStatusText = status.lastError
  493. ? `错误: ${status.lastError}`
  494. : status.lastSentAt
  495. ? `${status.lastSentTopic || 'unknown'} @ ${formatClockTime(status.lastSentAt)}`
  496. : '待命'
  497. updateUiState()
  498. } catch (_error) {
  499. state.bridgeEnabled = false
  500. state.bridgeConnected = false
  501. state.bridgeAuthenticated = false
  502. state.bridgeTargetText = '--'
  503. state.bridgeLastStatusText = '状态读取失败'
  504. updateUiState()
  505. }
  506. }
  507. async function loadGatewayBridgeConfig(options) {
  508. const preserveForm = Boolean(options && options.preserveForm)
  509. const response = await fetch('/bridge-config', {
  510. cache: 'no-store',
  511. })
  512. if (!response.ok) {
  513. throw new Error(`桥接配置读取失败: HTTP ${response.status}`)
  514. }
  515. const payload = await response.json()
  516. if (!preserveForm) {
  517. fillBridgeConfigForm(bridgeConfigFromServerPayload(payload))
  518. }
  519. return payload
  520. }
  521. async function applyGatewayBridgeConfig() {
  522. const config = readBridgeConfigForm()
  523. if (!config.url) {
  524. log('桥接配置缺少网关地址')
  525. return
  526. }
  527. if (!config.deviceId) {
  528. log('桥接配置缺少目标 Device ID')
  529. return
  530. }
  531. if (!config.sourceId) {
  532. log('桥接配置缺少 Source ID')
  533. return
  534. }
  535. state.bridgeConfigSaving = true
  536. updateUiState()
  537. try {
  538. const response = await fetch('/bridge-config', {
  539. method: 'POST',
  540. headers: {
  541. 'Content-Type': 'application/json',
  542. },
  543. body: JSON.stringify(config),
  544. })
  545. const payload = await response.json()
  546. if (!response.ok) {
  547. throw new Error(payload && payload.error ? payload.error : `HTTP ${response.status}`)
  548. }
  549. saveBridgeConfigDraft(config)
  550. fillBridgeConfigForm(bridgeConfigFromServerPayload(payload))
  551. await refreshGatewayBridgeStatus()
  552. log(`已应用新网关桥接配置 -> ${config.deviceId}`)
  553. } catch (error) {
  554. log(error && error.message ? error.message : '桥接配置应用失败')
  555. } finally {
  556. state.bridgeConfigSaving = false
  557. updateUiState()
  558. }
  559. }
  560. function proxyUrl(targetUrl) {
  561. return `${PROXY_BASE_URL}${encodeURIComponent(targetUrl)}`
  562. }
  563. async function fetchJson(targetUrl) {
  564. const response = await fetch(proxyUrl(targetUrl), { cache: 'no-store' })
  565. if (!response.ok) {
  566. throw new Error(`载入失败: ${response.status} ${targetUrl}`)
  567. }
  568. const text = await response.text()
  569. return parseJsonWithFallback(text)
  570. }
  571. async function fetchText(targetUrl) {
  572. const response = await fetch(proxyUrl(targetUrl), { cache: 'no-store' })
  573. if (!response.ok) {
  574. throw new Error(`载入失败: ${response.status} ${targetUrl}`)
  575. }
  576. return response.text()
  577. }
  578. function parseJsonWithFallback(text) {
  579. try {
  580. return JSON.parse(text)
  581. } catch (_error) {
  582. const sanitized = text
  583. .replace(/,\s*"center"\s*:\s*\[[^\]]*\]\s*(?=[}\r\n])/g, '')
  584. .replace(/"center"\s*:\s*\[[^\]]*\]\s*,/g, '')
  585. .replace(/,\s*([}\]])/g, '$1')
  586. return JSON.parse(sanitized)
  587. }
  588. }
  589. function resolveUrl(baseUrl, relativePath) {
  590. const trimmed = String(relativePath || '').trim()
  591. if (!trimmed) {
  592. return ''
  593. }
  594. if (/^https?:\/\//i.test(trimmed)) {
  595. return trimmed
  596. }
  597. const url = new URL(baseUrl)
  598. if (trimmed.startsWith('/')) {
  599. return `${url.origin}${trimmed}`
  600. }
  601. const baseDir = baseUrl.slice(0, baseUrl.lastIndexOf('/') + 1)
  602. return `${baseDir}${trimmed.replace(/^\.\//, '')}`
  603. }
  604. function joinUrl(rootUrl, relativePath) {
  605. const normalizedRoot = String(rootUrl || '').replace(/\/+$/, '')
  606. const normalizedPath = String(relativePath || '').replace(/^\/+/, '')
  607. return `${normalizedRoot}/${normalizedPath}`
  608. }
  609. function webMercatorToLatLng(x, y) {
  610. const lon = x / 20037508.34 * 180
  611. let lat = y / 20037508.34 * 180
  612. lat = 180 / Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180)) - Math.PI / 2)
  613. return L.latLng(lat, lon)
  614. }
  615. function applyTileTemplate(tileUrl, options) {
  616. const trimmed = String(tileUrl || '').trim()
  617. if (!trimmed) {
  618. throw new Error('瓦片模板不能为空')
  619. }
  620. if (tileLayer) {
  621. map.removeLayer(tileLayer)
  622. }
  623. tileLayer = createTileLayer(trimmed, options || {}).addTo(map)
  624. elements.tileUrlInput.value = trimmed
  625. }
  626. function fitBoundsFromMercator(bounds) {
  627. if (!Array.isArray(bounds) || bounds.length !== 4) {
  628. return
  629. }
  630. const southWest = webMercatorToLatLng(Number(bounds[0]), Number(bounds[1]))
  631. const northEast = webMercatorToLatLng(Number(bounds[2]), Number(bounds[3]))
  632. map.fitBounds(L.latLngBounds(southWest, northEast), { padding: [24, 24] })
  633. }
  634. function parseCoordinateTuple(rawValue) {
  635. const parts = rawValue.trim().split(',')
  636. if (parts.length < 2) {
  637. return null
  638. }
  639. const lon = Number(parts[0])
  640. const lat = Number(parts[1])
  641. if (!Number.isFinite(lon) || !Number.isFinite(lat)) {
  642. return null
  643. }
  644. return { lat, lon }
  645. }
  646. function extractPointCoordinates(block) {
  647. const pointMatch = block.match(/<Point\b[\s\S]*?<coordinates>([\s\S]*?)<\/coordinates>[\s\S]*?<\/Point>/i)
  648. if (!pointMatch) {
  649. return null
  650. }
  651. const coordinateMatch = pointMatch[1].trim().match(/-?\d+(?:\.\d+)?,-?\d+(?:\.\d+)?(?:,-?\d+(?:\.\d+)?)?/)
  652. return coordinateMatch ? parseCoordinateTuple(coordinateMatch[0]) : null
  653. }
  654. function decodeXmlEntities(text) {
  655. return text
  656. .replace(/&lt;/g, '<')
  657. .replace(/&gt;/g, '>')
  658. .replace(/&quot;/g, '"')
  659. .replace(/&#39;/g, "'")
  660. .replace(/&apos;/g, "'")
  661. .replace(/&amp;/g, '&')
  662. }
  663. function stripXml(text) {
  664. return decodeXmlEntities(String(text || '').replace(/<[^>]+>/g, ' ')).replace(/\s+/g, ' ').trim()
  665. }
  666. function extractTagText(block, tagName) {
  667. const match = block.match(new RegExp(`<${tagName}\\b[^>]*>([\\s\\S]*?)<\\/${tagName}>`, 'i'))
  668. return match ? stripXml(match[1]) : ''
  669. }
  670. function normalizeCourseLabel(label) {
  671. return String(label || '').trim().replace(/\s+/g, ' ')
  672. }
  673. function inferExplicitKind(label, placemarkBlock) {
  674. const normalized = normalizeCourseLabel(label).toUpperCase().replace(/[^A-Z0-9]/g, '')
  675. const styleHint = String(placemarkBlock || '').toUpperCase()
  676. if (
  677. normalized === 'S'
  678. || normalized.startsWith('START')
  679. || /^S\d+$/.test(normalized)
  680. || styleHint.includes('START')
  681. || styleHint.includes('TRIANGLE')
  682. ) {
  683. return 'start'
  684. }
  685. if (
  686. normalized === 'F'
  687. || normalized === 'M'
  688. || normalized.startsWith('FINISH')
  689. || normalized.startsWith('GOAL')
  690. || /^F\d+$/.test(normalized)
  691. || styleHint.includes('FINISH')
  692. || styleHint.includes('GOAL')
  693. ) {
  694. return 'finish'
  695. }
  696. return null
  697. }
  698. function extractPlacemarkPoints(kmlText) {
  699. const placemarkBlocks = kmlText.match(/<Placemark\b[\s\S]*?<\/Placemark>/gi) || []
  700. const points = []
  701. placemarkBlocks.forEach((placemarkBlock) => {
  702. const point = extractPointCoordinates(placemarkBlock)
  703. if (!point) {
  704. return
  705. }
  706. const label = normalizeCourseLabel(extractTagText(placemarkBlock, 'name'))
  707. points.push({
  708. label,
  709. point,
  710. explicitKind: inferExplicitKind(label, placemarkBlock),
  711. })
  712. })
  713. return points
  714. }
  715. function classifyOrderedNodes(points) {
  716. if (!points.length) {
  717. return []
  718. }
  719. const startIndex = points.findIndex((point) => point.explicitKind === 'start')
  720. let finishIndex = -1
  721. for (let index = points.length - 1; index >= 0; index -= 1) {
  722. if (points[index].explicitKind === 'finish') {
  723. finishIndex = index
  724. break
  725. }
  726. }
  727. return points.map((point, index) => {
  728. let kind = point.explicitKind
  729. if (!kind) {
  730. if (startIndex === -1 && index === 0) {
  731. kind = 'start'
  732. } else if (finishIndex === -1 && points.length > 1 && index === points.length - 1) {
  733. kind = 'finish'
  734. } else {
  735. kind = 'control'
  736. }
  737. }
  738. return {
  739. label: point.label,
  740. point: point.point,
  741. kind,
  742. }
  743. })
  744. }
  745. function parseCourseKml(kmlText) {
  746. const points = extractPlacemarkPoints(kmlText)
  747. if (!points.length) {
  748. throw new Error('KML 中没有可用的 Point 控制点')
  749. }
  750. const nodes = classifyOrderedNodes(points)
  751. const starts = []
  752. const controls = []
  753. const finishes = []
  754. let controlSequence = 1
  755. nodes.forEach((node) => {
  756. if (node.kind === 'start') {
  757. starts.push({
  758. label: node.label || 'Start',
  759. point: node.point,
  760. })
  761. return
  762. }
  763. if (node.kind === 'finish') {
  764. finishes.push({
  765. label: node.label || 'Finish',
  766. point: node.point,
  767. })
  768. return
  769. }
  770. controls.push({
  771. label: node.label || String(controlSequence),
  772. sequence: controlSequence,
  773. point: node.point,
  774. })
  775. controlSequence += 1
  776. })
  777. return {
  778. title: extractTagText(kmlText, 'name') || 'Orienteering Course',
  779. starts,
  780. controls,
  781. finishes,
  782. }
  783. }
  784. function buildDivIcon(className, html, size) {
  785. return L.divIcon({
  786. className,
  787. html,
  788. iconSize: size,
  789. iconAnchor: [size[0] / 2, size[1] / 2],
  790. })
  791. }
  792. function setCurrentPosition(lat, lon) {
  793. state.currentLatLng = L.latLng(lat, lon)
  794. updateReadout()
  795. }
  796. function jumpToPoint(lat, lon, zoom) {
  797. setCurrentPosition(lat, lon)
  798. map.flyTo([lat, lon], zoom || Math.max(map.getZoom(), 18), {
  799. duration: 0.6,
  800. })
  801. }
  802. function buildJumpChip(label, point, className) {
  803. const button = document.createElement('button')
  804. button.type = 'button'
  805. button.className = `jump-chip ${className || ''}`.trim()
  806. button.textContent = label
  807. button.addEventListener('click', () => {
  808. jumpToPoint(point.lat, point.lon, 19)
  809. log(`跳转到 ${label}`)
  810. })
  811. return button
  812. }
  813. function refreshCourseJumpList(course) {
  814. elements.courseJumpList.innerHTML = ''
  815. if (!course) {
  816. return
  817. }
  818. course.starts.forEach((item) => {
  819. elements.courseJumpList.appendChild(buildJumpChip('开始点', item.point, 'jump-chip--start'))
  820. })
  821. course.controls.forEach((item) => {
  822. elements.courseJumpList.appendChild(buildJumpChip(String(item.sequence), item.point, ''))
  823. })
  824. course.finishes.forEach((item) => {
  825. elements.courseJumpList.appendChild(buildJumpChip('结束点', item.point, 'jump-chip--finish'))
  826. })
  827. }
  828. function renderCourse(course) {
  829. courseLayer.clearLayers()
  830. state.loadedCourse = course
  831. refreshCourseJumpList(course)
  832. course.starts.forEach((item) => {
  833. const marker = L.marker([item.point.lat, item.point.lon], {
  834. icon: buildDivIcon('course-marker', '<div class="course-marker__start"></div>', [36, 36]),
  835. })
  836. marker.on('click', () => jumpToPoint(item.point.lat, item.point.lon, 19))
  837. marker.addTo(courseLayer)
  838. })
  839. course.controls.forEach((item) => {
  840. const marker = L.marker([item.point.lat, item.point.lon], {
  841. icon: buildDivIcon(
  842. 'course-marker',
  843. `<div class="course-marker__control">${item.sequence}</div>`,
  844. [40, 40],
  845. ),
  846. })
  847. marker.on('click', () => jumpToPoint(item.point.lat, item.point.lon, 19))
  848. marker.addTo(courseLayer)
  849. })
  850. course.finishes.forEach((item) => {
  851. const marker = L.marker([item.point.lat, item.point.lon], {
  852. icon: buildDivIcon('course-marker', '<div class="course-marker__finish"></div>', [40, 40]),
  853. })
  854. marker.on('click', () => jumpToPoint(item.point.lat, item.point.lon, 19))
  855. marker.addTo(courseLayer)
  856. })
  857. fitCourseBounds()
  858. updateUiState()
  859. }
  860. function clearCourse() {
  861. state.loadedCourse = null
  862. courseLayer.clearLayers()
  863. refreshCourseJumpList(null)
  864. setResourceStatus('已清空控制点', 'warn')
  865. state.lastResourceDetailText = '已清空控制点'
  866. updateUiState()
  867. }
  868. function fitCourseBounds() {
  869. if (!state.loadedCourse) {
  870. return
  871. }
  872. const latLngs = []
  873. state.loadedCourse.starts.forEach((item) => latLngs.push([item.point.lat, item.point.lon]))
  874. state.loadedCourse.controls.forEach((item) => latLngs.push([item.point.lat, item.point.lon]))
  875. state.loadedCourse.finishes.forEach((item) => latLngs.push([item.point.lat, item.point.lon]))
  876. if (!latLngs.length) {
  877. return
  878. }
  879. map.fitBounds(L.latLngBounds(latLngs), { padding: [30, 30] })
  880. }
  881. async function loadCourseFromUrl(courseUrl, shouldFit) {
  882. const trimmed = String(courseUrl || '').trim()
  883. if (!trimmed) {
  884. throw new Error('KML 地址不能为空')
  885. }
  886. const kmlText = await fetchText(trimmed)
  887. const course = parseCourseKml(kmlText)
  888. renderCourse(course)
  889. elements.courseUrlInput.value = trimmed
  890. if (shouldFit !== false) {
  891. fitCourseBounds()
  892. }
  893. setResourceStatus(`已载入控制点: ${course.title}`, 'ok')
  894. state.lastResourceDetailText = `最近资源: 控制点 ${course.title} (${formatClockTime(Date.now())})`
  895. log(`已载入 KML: ${trimmed}`)
  896. updateUiState()
  897. }
  898. async function loadConfigResources() {
  899. const configUrl = String(elements.configUrlInput.value || '').trim()
  900. if (!configUrl) {
  901. setResourceStatus('请先填写 game.json 地址', 'warn')
  902. return
  903. }
  904. state.resourceLoading = true
  905. updateUiState()
  906. setResourceStatus('正在载入配置...', null)
  907. try {
  908. const config = await fetchJson(configUrl)
  909. let mapStatus = '未找到瓦片配置'
  910. if (config.map && config.mapmeta) {
  911. const mapRootUrl = resolveUrl(configUrl, config.map)
  912. const mapMetaUrl = resolveUrl(configUrl, config.mapmeta)
  913. const mapMeta = await fetchJson(mapMetaUrl)
  914. const tilePathTemplate = mapMeta.tilePathTemplate || `{z}/{x}/{y}.${mapMeta.tileFormat || 'png'}`
  915. const tileTemplateUrl = /^https?:\/\//i.test(tilePathTemplate)
  916. ? tilePathTemplate
  917. : joinUrl(mapRootUrl, tilePathTemplate)
  918. applyTileTemplate(tileTemplateUrl, {
  919. minZoom: Number.isFinite(mapMeta.minZoom) ? mapMeta.minZoom : 16,
  920. maxZoom: Number.isFinite(mapMeta.maxZoom) ? mapMeta.maxZoom : 20,
  921. attribution: 'Custom Map',
  922. })
  923. mapStatus = '已载入瓦片'
  924. if (Array.isArray(mapMeta.bounds) && mapMeta.bounds.length === 4) {
  925. fitBoundsFromMercator(mapMeta.bounds)
  926. }
  927. }
  928. let courseStatus = '未找到 KML 配置'
  929. if (config.course) {
  930. const courseUrl = resolveUrl(configUrl, config.course)
  931. elements.courseUrlInput.value = courseUrl
  932. await loadCourseFromUrl(courseUrl, false)
  933. courseStatus = '已载入控制点'
  934. }
  935. setResourceStatus(`配置已载入: ${mapStatus} / ${courseStatus}`, 'ok')
  936. state.lastResourceDetailText = `最近资源: 配置 ${formatClockTime(Date.now())}`
  937. log(`已载入配置: ${configUrl}`)
  938. } catch (error) {
  939. const message = error && error.message ? error.message : '未知错误'
  940. setResourceStatus(`配置载入失败: ${message}`, 'warn')
  941. log(`配置载入失败: ${message}`)
  942. } finally {
  943. state.resourceLoading = false
  944. updateUiState()
  945. }
  946. }
  947. function getAccuracy() {
  948. return Math.max(1, Number(elements.accuracyInput.value) || 6)
  949. }
  950. function getSpeedMps() {
  951. return Math.max(0.2, (Number(elements.speedInput.value) || 6) / 3.6)
  952. }
  953. function getHeartRateBpm() {
  954. return Math.max(40, Math.min(220, Math.round(Number(elements.heartRateInput.value) || 120)))
  955. }
  956. function getSampleHeartRateBpm() {
  957. const now = Date.now()
  958. if (!state.heartRateSampleStartedAt) {
  959. state.heartRateSampleStartedAt = now
  960. }
  961. const elapsedSeconds = (now - state.heartRateSampleStartedAt) / 1000
  962. const template = elements.heartRateSampleTemplateSelect.value || 'jog'
  963. let cycleSeconds = 360
  964. let bpm = 120
  965. const jitter = Math.sin(elapsedSeconds * 1.7) * 1.8 + Math.sin(elapsedSeconds * 0.47) * 1.2
  966. if (template === 'recovery') {
  967. cycleSeconds = 300
  968. const phase = elapsedSeconds % cycleSeconds
  969. if (phase < 80) {
  970. bpm = 82 + phase * 0.08
  971. } else if (phase < 190) {
  972. bpm = 89 + Math.sin((phase - 80) / 20) * 3
  973. } else {
  974. bpm = 90 - (phase - 190) * 0.06 + Math.sin((phase - 190) / 18) * 2
  975. }
  976. } else if (template === 'tempo') {
  977. cycleSeconds = 320
  978. const phase = elapsedSeconds % cycleSeconds
  979. if (phase < 50) {
  980. bpm = 102 + phase * 0.42
  981. } else if (phase < 230) {
  982. bpm = 124 + Math.sin((phase - 50) / 14) * 5 + Math.sin((phase - 50) / 36) * 3
  983. } else {
  984. bpm = 126 - (phase - 230) * 0.18 + Math.sin((phase - 230) / 12) * 3
  985. }
  986. } else if (template === 'interval') {
  987. cycleSeconds = 260
  988. const phase = elapsedSeconds % cycleSeconds
  989. if (phase < 40) {
  990. bpm = 100 + phase * 0.35
  991. } else {
  992. const wavePhase = phase - 40
  993. const intervalCycle = wavePhase % 44
  994. if (intervalCycle < 20) {
  995. bpm = 140 + intervalCycle * 1.2
  996. } else if (intervalCycle < 32) {
  997. bpm = 164 - (intervalCycle - 20) * 0.45
  998. } else {
  999. bpm = 158 - (intervalCycle - 32) * 2.7
  1000. }
  1001. }
  1002. } else {
  1003. const phase = elapsedSeconds % cycleSeconds
  1004. if (phase < 60) {
  1005. bpm = 96 + phase * 0.35
  1006. } else if (phase < 150) {
  1007. bpm = 118 + Math.sin((phase - 60) / 18) * 6
  1008. } else if (phase < 240) {
  1009. bpm = 138 + Math.sin((phase - 150) / 10) * 9
  1010. } else if (phase < 300) {
  1011. bpm = 158 + Math.sin((phase - 240) / 7) * 8
  1012. } else {
  1013. bpm = 124 - (phase - 300) * 0.22 + Math.sin((phase - 300) / 15) * 4
  1014. }
  1015. }
  1016. const nextBpm = Math.max(72, Math.min(182, Math.round(bpm + jitter)))
  1017. elements.heartRateInput.value = String(nextBpm)
  1018. return nextBpm
  1019. }
  1020. function sendCurrentPoint() {
  1021. if (!state.socket || state.socket.readyState !== WebSocket.OPEN) {
  1022. log('未连接桥接,无法发送')
  1023. return
  1024. }
  1025. const payload = {
  1026. type: 'mock_gps',
  1027. timestamp: Date.now(),
  1028. lat: Number(state.currentLatLng.lat.toFixed(6)),
  1029. lon: Number(state.currentLatLng.lng.toFixed(6)),
  1030. accuracyMeters: getAccuracy(),
  1031. speedMps: Number(getSpeedMps().toFixed(2)),
  1032. headingDeg: Number(state.headingDeg.toFixed(1)),
  1033. }
  1034. state.socket.send(JSON.stringify(payload))
  1035. state.lastSentText = `${formatClockTime(payload.timestamp)} @ ${payload.lat.toFixed(6)}, ${payload.lon.toFixed(6)}`
  1036. updateUiState()
  1037. }
  1038. function sendCurrentHeartRate() {
  1039. if (!state.socket || state.socket.readyState !== WebSocket.OPEN) {
  1040. log('未连接桥接,无法发送心率')
  1041. return
  1042. }
  1043. const payload = {
  1044. type: 'mock_heart_rate',
  1045. timestamp: Date.now(),
  1046. bpm: state.heartRateSampleMode ? getSampleHeartRateBpm() : getHeartRateBpm(),
  1047. }
  1048. state.socket.send(JSON.stringify(payload))
  1049. state.lastHeartRateSentText = `${formatClockTime(payload.timestamp)} @ ${payload.bpm} bpm`
  1050. updateUiState()
  1051. }
  1052. function startStream() {
  1053. stopStream()
  1054. state.streaming = true
  1055. const intervalMs = Math.max(80, 1000 / (Number(elements.hzSelect.value) || 5))
  1056. sendCurrentPoint()
  1057. state.streamTimer = window.setInterval(sendCurrentPoint, intervalMs)
  1058. updateUiState()
  1059. log(`开始连续发送 (${Math.round(1000 / intervalMs)} Hz)`)
  1060. }
  1061. function stopStream() {
  1062. state.streaming = false
  1063. if (state.streamTimer) {
  1064. window.clearInterval(state.streamTimer)
  1065. state.streamTimer = 0
  1066. log('已停止连续发送')
  1067. }
  1068. updateUiState()
  1069. }
  1070. function startHeartRateStream() {
  1071. stopHeartRateStream()
  1072. state.heartRateStreaming = true
  1073. if (state.heartRateSampleMode && !state.heartRateSampleStartedAt) {
  1074. state.heartRateSampleStartedAt = Date.now()
  1075. }
  1076. const intervalMs = Math.max(150, 1000 / (Number(elements.heartRateHzSelect.value) || 1))
  1077. sendCurrentHeartRate()
  1078. state.heartRateStreamTimer = window.setInterval(sendCurrentHeartRate, intervalMs)
  1079. updateUiState()
  1080. log(`开始连续发送心率 (${Math.round(1000 / intervalMs)} Hz)`)
  1081. }
  1082. function stopHeartRateStream() {
  1083. state.heartRateStreaming = false
  1084. if (state.heartRateStreamTimer) {
  1085. window.clearInterval(state.heartRateStreamTimer)
  1086. state.heartRateStreamTimer = 0
  1087. log('已停止连续发送心率')
  1088. }
  1089. updateUiState()
  1090. }
  1091. function applyHeartRatePreset() {
  1092. const sampleBpm = [88, 102, 118, 136, 154, 170]
  1093. const current = getHeartRateBpm()
  1094. let nextIndex = sampleBpm.findIndex((value) => value > current)
  1095. if (nextIndex === -1) {
  1096. nextIndex = 0
  1097. }
  1098. elements.heartRateInput.value = String(sampleBpm[nextIndex])
  1099. log(`已应用心率分区样本: ${sampleBpm[nextIndex]} bpm`)
  1100. }
  1101. function toggleHeartRateSampleMode() {
  1102. state.heartRateSampleMode = !state.heartRateSampleMode
  1103. state.heartRateSampleStartedAt = state.heartRateSampleMode ? Date.now() : 0
  1104. if (state.heartRateSampleMode) {
  1105. const bpm = getSampleHeartRateBpm()
  1106. log(`已开启真实心率样本 (${elements.heartRateSampleTemplateSelect.value || 'jog'}): ${bpm} bpm`)
  1107. } else {
  1108. log('已关闭真实心率样本')
  1109. }
  1110. updateUiState()
  1111. }
  1112. function syncPathLine() {
  1113. pathLine.setLatLngs(pathPoints)
  1114. elements.pathCountText.textContent = String(pathPoints.length)
  1115. updateUiState()
  1116. }
  1117. function clearPathMarkers() {
  1118. while (pathMarkers.length) {
  1119. map.removeLayer(pathMarkers.pop())
  1120. }
  1121. }
  1122. function refreshPathMarkers() {
  1123. clearPathMarkers()
  1124. pathPoints.forEach((point, index) => {
  1125. const marker = L.circleMarker(point, {
  1126. radius: 5,
  1127. color: '#ffffff',
  1128. weight: 2,
  1129. fillColor: index === 0 ? '#0ea5a4' : '#0b625b',
  1130. fillOpacity: 0.95,
  1131. }).addTo(map)
  1132. pathMarkers.push(marker)
  1133. })
  1134. }
  1135. function addPathPoint(latlng) {
  1136. pathPoints.push(L.latLng(latlng.lat, latlng.lng))
  1137. state.lastTrackSourceText = '手工路径'
  1138. syncPathLine()
  1139. refreshPathMarkers()
  1140. }
  1141. function fitPathBounds() {
  1142. if (pathPoints.length < 2) {
  1143. return
  1144. }
  1145. map.fitBounds(L.latLngBounds(pathPoints), { padding: [30, 30] })
  1146. }
  1147. function replacePathPoints(nextPoints, sourceLabel) {
  1148. pathPoints.splice(0, pathPoints.length)
  1149. nextPoints.forEach((point) => {
  1150. pathPoints.push(L.latLng(point.lat, point.lng))
  1151. })
  1152. state.lastTrackSourceText = sourceLabel
  1153. stopPlayback()
  1154. syncPathLine()
  1155. refreshPathMarkers()
  1156. if (pathPoints.length) {
  1157. state.currentLatLng = L.latLng(pathPoints[0].lat, pathPoints[0].lng)
  1158. updateReadout()
  1159. }
  1160. if (pathPoints.length >= 2) {
  1161. fitPathBounds()
  1162. }
  1163. }
  1164. function parseGeoJsonTrack(rawValue) {
  1165. const latLngs = []
  1166. function pushLngLat(coords) {
  1167. if (!Array.isArray(coords) || coords.length < 2) {
  1168. return
  1169. }
  1170. const lng = Number(coords[0])
  1171. const lat = Number(coords[1])
  1172. if (Number.isFinite(lat) && Number.isFinite(lng)) {
  1173. latLngs.push({ lat, lng })
  1174. }
  1175. }
  1176. function walk(node) {
  1177. if (!node || typeof node !== 'object') {
  1178. return
  1179. }
  1180. if (node.type === 'FeatureCollection' && Array.isArray(node.features)) {
  1181. node.features.forEach(walk)
  1182. return
  1183. }
  1184. if (node.type === 'Feature' && node.geometry) {
  1185. walk(node.geometry)
  1186. return
  1187. }
  1188. if (node.type === 'LineString' && Array.isArray(node.coordinates)) {
  1189. node.coordinates.forEach(pushLngLat)
  1190. return
  1191. }
  1192. if (node.type === 'MultiLineString' && Array.isArray(node.coordinates)) {
  1193. node.coordinates.forEach((line) => {
  1194. if (Array.isArray(line)) {
  1195. line.forEach(pushLngLat)
  1196. }
  1197. })
  1198. }
  1199. }
  1200. if (Array.isArray(rawValue)) {
  1201. rawValue.forEach((item) => {
  1202. if (Array.isArray(item)) {
  1203. pushLngLat(item)
  1204. return
  1205. }
  1206. if (item && typeof item === 'object') {
  1207. const lat = Number(item.lat)
  1208. const lng = Number(item.lng !== undefined ? item.lng : item.lon)
  1209. if (Number.isFinite(lat) && Number.isFinite(lng)) {
  1210. latLngs.push({ lat, lng })
  1211. }
  1212. }
  1213. })
  1214. return latLngs
  1215. }
  1216. walk(rawValue)
  1217. return latLngs
  1218. }
  1219. function parseGpxTrack(text) {
  1220. const xml = new DOMParser().parseFromString(text, 'application/xml')
  1221. const latLngs = []
  1222. const trackPoints = Array.from(xml.querySelectorAll('trkpt'))
  1223. const routePoints = trackPoints.length ? [] : Array.from(xml.querySelectorAll('rtept'))
  1224. const nodes = trackPoints.length ? trackPoints : routePoints
  1225. nodes.forEach((node) => {
  1226. const lat = Number(node.getAttribute('lat'))
  1227. const lng = Number(node.getAttribute('lon'))
  1228. if (Number.isFinite(lat) && Number.isFinite(lng)) {
  1229. latLngs.push({ lat, lng })
  1230. }
  1231. })
  1232. return latLngs
  1233. }
  1234. function parseKmlTrack(text) {
  1235. const xml = new DOMParser().parseFromString(text, 'application/xml')
  1236. const latLngs = []
  1237. const lineStrings = Array.from(xml.querySelectorAll('LineString coordinates'))
  1238. lineStrings.forEach((node) => {
  1239. String(node.textContent || '')
  1240. .trim()
  1241. .split(/\s+/)
  1242. .forEach((tuple) => {
  1243. const parsed = parseCoordinateTuple(tuple)
  1244. if (parsed) {
  1245. latLngs.push({ lat: parsed.lat, lng: parsed.lon })
  1246. }
  1247. })
  1248. })
  1249. return latLngs
  1250. }
  1251. function parseTrackFile(fileName, text) {
  1252. const lowerName = String(fileName || '').toLowerCase()
  1253. if (lowerName.endsWith('.gpx')) {
  1254. return parseGpxTrack(text)
  1255. }
  1256. if (lowerName.endsWith('.kml')) {
  1257. return parseKmlTrack(text)
  1258. }
  1259. if (lowerName.endsWith('.geojson') || lowerName.endsWith('.json')) {
  1260. return parseGeoJsonTrack(parseJsonWithFallback(text))
  1261. }
  1262. if (text.includes('<gpx')) {
  1263. return parseGpxTrack(text)
  1264. }
  1265. if (text.includes('<kml') || text.includes('<LineString')) {
  1266. return parseKmlTrack(text)
  1267. }
  1268. return parseGeoJsonTrack(parseJsonWithFallback(text))
  1269. }
  1270. async function handleTrackFileSelected(file) {
  1271. if (!file) {
  1272. return
  1273. }
  1274. try {
  1275. const text = await file.text()
  1276. const latLngs = parseTrackFile(file.name, text)
  1277. if (!latLngs || latLngs.length < 2) {
  1278. throw new Error('轨迹文件中没有可回放的路径点')
  1279. }
  1280. replacePathPoints(latLngs, `轨迹文件 ${file.name}`)
  1281. log(`已导入轨迹文件: ${file.name} (${latLngs.length} 点)`)
  1282. } catch (error) {
  1283. const message = error && error.message ? error.message : '轨迹文件导入失败'
  1284. log(message)
  1285. alert(message)
  1286. } finally {
  1287. elements.trackFileInput.value = ''
  1288. }
  1289. }
  1290. function toRad(value) {
  1291. return value * Math.PI / 180
  1292. }
  1293. function toDeg(value) {
  1294. return value * 180 / Math.PI
  1295. }
  1296. function getDistanceMeters(from, to) {
  1297. const earth = 6371000
  1298. const lat1 = toRad(from.lat)
  1299. const lat2 = toRad(to.lat)
  1300. const dLat = lat2 - lat1
  1301. const dLon = toRad(to.lng - from.lng)
  1302. const a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
  1303. + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) * Math.sin(dLon / 2)
  1304. return earth * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
  1305. }
  1306. function getHeadingDeg(from, to) {
  1307. const lat1 = toRad(from.lat)
  1308. const lat2 = toRad(to.lat)
  1309. const dLon = toRad(to.lng - from.lng)
  1310. const y = Math.sin(dLon) * Math.cos(lat2)
  1311. const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon)
  1312. const bearing = (toDeg(Math.atan2(y, x)) + 360) % 360
  1313. return bearing
  1314. }
  1315. function interpolateLatLng(from, to, t) {
  1316. return L.latLng(
  1317. from.lat + (to.lat - from.lat) * t,
  1318. from.lng + (to.lng - from.lng) * t,
  1319. )
  1320. }
  1321. function tickPlayback() {
  1322. if (!state.playbackRunning || pathPoints.length < 2) {
  1323. return
  1324. }
  1325. const now = performance.now()
  1326. if (!state.lastPlaybackAt) {
  1327. state.lastPlaybackAt = now
  1328. }
  1329. const deltaSeconds = (now - state.lastPlaybackAt) / 1000
  1330. state.lastPlaybackAt = now
  1331. let remainingTravel = getSpeedMps() * deltaSeconds
  1332. while (remainingTravel > 0 && state.currentSegmentIndex < pathPoints.length - 1) {
  1333. const from = pathPoints[state.currentSegmentIndex]
  1334. const to = pathPoints[state.currentSegmentIndex + 1]
  1335. const segmentDistance = getDistanceMeters(from, to)
  1336. if (!segmentDistance) {
  1337. state.currentSegmentIndex += 1
  1338. state.currentSegmentProgress = 0
  1339. continue
  1340. }
  1341. const remainingSegment = segmentDistance * (1 - state.currentSegmentProgress)
  1342. if (remainingTravel >= remainingSegment) {
  1343. remainingTravel -= remainingSegment
  1344. state.currentSegmentIndex += 1
  1345. state.currentSegmentProgress = 0
  1346. state.currentLatLng = L.latLng(to.lat, to.lng)
  1347. state.headingDeg = getHeadingDeg(from, to)
  1348. } else {
  1349. state.currentSegmentProgress += remainingTravel / segmentDistance
  1350. state.currentLatLng = interpolateLatLng(from, to, state.currentSegmentProgress)
  1351. state.headingDeg = getHeadingDeg(from, to)
  1352. remainingTravel = 0
  1353. }
  1354. }
  1355. if (state.currentSegmentIndex >= pathPoints.length - 1) {
  1356. if (elements.loopPathInput.checked) {
  1357. state.currentSegmentIndex = 0
  1358. state.currentSegmentProgress = 0
  1359. state.currentLatLng = L.latLng(pathPoints[0].lat, pathPoints[0].lng)
  1360. } else {
  1361. stopPlayback()
  1362. }
  1363. }
  1364. updateReadout()
  1365. if (state.streaming) {
  1366. sendCurrentPoint()
  1367. }
  1368. if (state.playbackRunning) {
  1369. state.playbackTimer = window.requestAnimationFrame(tickPlayback)
  1370. }
  1371. }
  1372. function startPlayback() {
  1373. if (pathPoints.length < 2) {
  1374. log('至少需要两个路径点')
  1375. return
  1376. }
  1377. stopPlayback()
  1378. state.playbackRunning = true
  1379. state.currentSegmentIndex = 0
  1380. state.currentSegmentProgress = 0
  1381. state.currentLatLng = L.latLng(pathPoints[0].lat, pathPoints[0].lng)
  1382. state.lastPlaybackAt = 0
  1383. updateReadout()
  1384. updateUiState()
  1385. log('开始路径回放')
  1386. state.playbackTimer = window.requestAnimationFrame(tickPlayback)
  1387. }
  1388. function stopPlayback() {
  1389. state.playbackRunning = false
  1390. state.lastPlaybackAt = 0
  1391. if (state.playbackTimer) {
  1392. window.cancelAnimationFrame(state.playbackTimer)
  1393. state.playbackTimer = 0
  1394. }
  1395. updateUiState()
  1396. }
  1397. map.on('click', (event) => {
  1398. if (state.pathEditMode) {
  1399. addPathPoint(event.latlng)
  1400. return
  1401. }
  1402. setCurrentPosition(event.latlng.lat, event.latlng.lng)
  1403. })
  1404. liveMarker.on('mousedown', () => {
  1405. map.dragging.disable()
  1406. })
  1407. map.on('mousemove', (event) => {
  1408. if (event.originalEvent.buttons !== 1) {
  1409. return
  1410. }
  1411. if (state.pathEditMode) {
  1412. return
  1413. }
  1414. setCurrentPosition(event.latlng.lat, event.latlng.lng)
  1415. })
  1416. map.on('mouseup', () => {
  1417. map.dragging.enable()
  1418. })
  1419. elements.connectBtn.addEventListener('click', connectSocket)
  1420. elements.applyGatewayBridgePresetBtn.addEventListener('click', applyBridgePresetToForm)
  1421. elements.saveGatewayBridgePresetBtn.addEventListener('click', saveCurrentBridgePreset)
  1422. elements.deleteGatewayBridgePresetBtn.addEventListener('click', deleteSelectedBridgePreset)
  1423. elements.gatewayBridgePresetSelect.addEventListener('change', () => {
  1424. const preset = selectedBridgePreset()
  1425. elements.gatewayBridgePresetNameInput.value = preset ? preset.name : ''
  1426. updateUiState()
  1427. })
  1428. elements.applyGatewayBridgeConfigBtn.addEventListener('click', applyGatewayBridgeConfig)
  1429. elements.reloadGatewayBridgeConfigBtn.addEventListener('click', async () => {
  1430. try {
  1431. await loadGatewayBridgeConfig()
  1432. await refreshGatewayBridgeStatus()
  1433. log('已重新读取桥接配置')
  1434. } catch (error) {
  1435. log(error && error.message ? error.message : '桥接配置读取失败')
  1436. }
  1437. })
  1438. elements.importTrackBtn.addEventListener('click', () => {
  1439. elements.trackFileInput.click()
  1440. })
  1441. elements.trackFileInput.addEventListener('change', (event) => {
  1442. const input = event.target
  1443. const file = input && input.files && input.files[0] ? input.files[0] : null
  1444. handleTrackFileSelected(file)
  1445. })
  1446. elements.loadConfigBtn.addEventListener('click', loadConfigResources)
  1447. elements.fitCourseBtn.addEventListener('click', fitCourseBounds)
  1448. elements.applyTilesBtn.addEventListener('click', () => {
  1449. try {
  1450. applyTileTemplate(elements.tileUrlInput.value, { attribution: 'Custom Map' })
  1451. setResourceStatus('已应用自定义瓦片', 'ok')
  1452. state.lastResourceDetailText = `最近资源: 自定义瓦片 ${formatClockTime(Date.now())}`
  1453. updateUiState()
  1454. } catch (error) {
  1455. setResourceStatus(error && error.message ? error.message : '瓦片应用失败', 'warn')
  1456. }
  1457. })
  1458. elements.resetTilesBtn.addEventListener('click', () => {
  1459. applyTileTemplate(DEFAULT_TILE_URL, {
  1460. maxZoom: 20,
  1461. attribution: '&copy; OpenStreetMap',
  1462. })
  1463. setResourceStatus('已恢复 OSM 底图', 'ok')
  1464. state.lastResourceDetailText = `最近资源: OSM 底图 ${formatClockTime(Date.now())}`
  1465. updateUiState()
  1466. })
  1467. elements.loadCourseBtn.addEventListener('click', async () => {
  1468. try {
  1469. await loadCourseFromUrl(elements.courseUrlInput.value, true)
  1470. } catch (error) {
  1471. const message = error && error.message ? error.message : 'KML 载入失败'
  1472. setResourceStatus(message, 'warn')
  1473. log(message)
  1474. }
  1475. })
  1476. elements.clearCourseBtn.addEventListener('click', clearCourse)
  1477. elements.fitPathBtn.addEventListener('click', fitPathBounds)
  1478. elements.sendOnceBtn.addEventListener('click', () => {
  1479. sendCurrentPoint()
  1480. log('已发送当前位置')
  1481. })
  1482. elements.streamBtn.addEventListener('click', startStream)
  1483. elements.stopStreamBtn.addEventListener('click', stopStream)
  1484. elements.sendHeartRateOnceBtn.addEventListener('click', () => {
  1485. sendCurrentHeartRate()
  1486. log('已发送当前心率')
  1487. })
  1488. elements.startHeartRateStreamBtn.addEventListener('click', startHeartRateStream)
  1489. elements.stopHeartRateStreamBtn.addEventListener('click', stopHeartRateStream)
  1490. elements.applyHeartRatePresetBtn.addEventListener('click', applyHeartRatePreset)
  1491. elements.toggleHeartRateSampleBtn.addEventListener('click', toggleHeartRateSampleMode)
  1492. elements.togglePathModeBtn.addEventListener('click', () => {
  1493. state.pathEditMode = !state.pathEditMode
  1494. elements.pathHint.textContent = state.pathEditMode
  1495. ? '地图点击将按顺序追加路径点。'
  1496. : '点击“开启路径编辑”后,在地图上逐点添加路径。'
  1497. updateUiState()
  1498. })
  1499. elements.clearPathBtn.addEventListener('click', () => {
  1500. pathPoints.splice(0, pathPoints.length)
  1501. state.lastTrackSourceText = '路径待命'
  1502. syncPathLine()
  1503. clearPathMarkers()
  1504. stopPlayback()
  1505. log('已清空路径')
  1506. })
  1507. elements.playPathBtn.addEventListener('click', startPlayback)
  1508. elements.pausePathBtn.addEventListener('click', () => {
  1509. stopPlayback()
  1510. log('已暂停回放')
  1511. })
  1512. updateReadout()
  1513. setSocketBadge(false)
  1514. setResourceStatus('支持直接载入 game.json,也支持单独填瓦片模板和 KML 地址。', null)
  1515. state.bridgePresets = loadBridgePresets()
  1516. renderBridgePresetOptions('')
  1517. updateUiState()
  1518. const draftBridgeConfig = getBridgeConfigDraft()
  1519. if (draftBridgeConfig) {
  1520. fillBridgeConfigForm(draftBridgeConfig)
  1521. }
  1522. loadGatewayBridgeConfig({ preserveForm: Boolean(draftBridgeConfig) })
  1523. .then(async () => {
  1524. if (draftBridgeConfig) {
  1525. log('已恢复上次桥接配置草稿,可直接点“应用桥接配置”')
  1526. }
  1527. await refreshGatewayBridgeStatus()
  1528. })
  1529. .catch((error) => {
  1530. log(error && error.message ? error.message : '桥接配置读取失败')
  1531. refreshGatewayBridgeStatus()
  1532. })
  1533. refreshGatewayBridgeStatus()
  1534. window.setInterval(refreshGatewayBridgeStatus, 3000)
  1535. connectSocket()
  1536. })()