fei.wang
6 天以前 ae7b22322555448d95fd56f505bafa325c167a26
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>报文文件管理器测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .test-section {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .result {
            background: #f5f5f5;
            padding: 10px;
            border-radius: 3px;
            margin: 10px 0;
            white-space: pre-wrap;
            font-family: monospace;
        }
        button {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 3px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover {
            background: #0056b3;
        }
        .success { color: green; }
        .error { color: red; }
        .warning { color: orange; }
    </style>
</head>
<body>
    <h1>报文文件管理器测试</h1>
    
    <div class="test-section">
        <h3>测试1: 初始化</h3>
        <button onclick="testInit()">测试初始化</button>
        <div id="init-result" class="result"></div>
    </div>
    
    <div class="test-section">
        <h3>测试2: 解析报文</h3>
        <button onclick="testParse()">测试解析</button>
        <div id="parse-result" class="result"></div>
    </div>
    
    <div class="test-section">
        <h3>测试3: 写入报文</h3>
        <button onclick="testWrite()">测试写入</button>
        <div id="write-result" class="result"></div>
    </div>
    
    <div class="test-section">
        <h3>测试4: 读取内容</h3>
        <button onclick="testRead()">测试读取</button>
        <div id="read-result" class="result"></div>
    </div>
    
    <div class="test-section">
        <h3>测试5: 模拟模式测试</h3>
        <button onclick="testSimulationMode()">测试模拟模式</button>
        <div id="simulation-result" class="result"></div>
    </div>
 
    <script>
        // 模拟uni-app环境(不包含getFileSystemManager)
        window.uni = {
            env: {
                USER_DATA_PATH: '/tmp'
            }
            // 故意不提供getFileSystemManager来测试模拟模式
        };
 
        // 导入报文文件管理器(完整版本)
        class MessageFileManager {
            constructor() {
                this.filePath = '';
                this.isInitialized = false;
                this.isSimulationMode = false;
                this.simulationContent = '';
            }
 
            async init() {
                try {
                    // 生成文件名:message_YYYYMMDD_HHMMSS.txt
                    const now = new Date();
                    const dateStr = now.getFullYear().toString() +
                        String(now.getMonth() + 1).padStart(2, '0') +
                        String(now.getDate()).padStart(2, '0');
                    const timeStr = String(now.getHours()).padStart(2, '0') +
                        String(now.getMinutes()).padStart(2, '0') +
                        String(now.getSeconds()).padStart(2, '0');
                    
                    const fileName = `message_${dateStr}_${timeStr}.txt`;
                    
                    // 检查uni-app环境是否可用
                    if (typeof uni === 'undefined') {
                        console.warn('uni-app环境不可用,使用模拟模式');
                        this.isSimulationMode = true;
                        this.filePath = `/tmp/${fileName}`;
                        this.isInitialized = true;
                        return this.filePath;
                    }
                    
                    // 获取用户数据目录,添加兼容性处理
                    let userDataPath = '';
                    try {
                        // 尝试获取uni.env.USER_DATA_PATH
                        if (uni && uni.env && uni.env.USER_DATA_PATH) {
                            userDataPath = uni.env.USER_DATA_PATH;
                        } else {
                            // 如果不可用,使用默认路径
                            userDataPath = '/tmp';
                            console.warn('uni.env.USER_DATA_PATH不可用,使用默认路径:', userDataPath);
                        }
                    } catch (error) {
                        console.warn('获取用户数据路径失败,使用默认路径:', error);
                        userDataPath = '/tmp';
                    }
                    
                    this.filePath = `${userDataPath}/${fileName}`;
                    
                    // 检查文件系统管理器是否可用
                    if (!uni.getFileSystemManager) {
                        console.warn('getFileSystemManager API不可用,使用模拟模式');
                        this.isSimulationMode = true;
                        this.isInitialized = true;
                        return this.filePath;
                    }
                    
                    // 创建文件并写入头部信息
                    await this.createMessageFile();
                    
                    // 确保初始化状态为true
                    this.isInitialized = true;
                    console.log('报文文件管理器初始化完成,文件路径:', this.filePath);
                    
                    return this.filePath;
                } catch (error) {
                    console.error('报文文件管理器初始化失败:', error);
                    // 即使出错也要设置初始化状态为true,使用模拟模式
                    this.isInitialized = true;
                    this.isSimulationMode = true;
                    console.warn('使用模拟模式继续运行');
                    return this.filePath || '/tmp/message_simulation.txt';
                }
            }
 
            async createMessageFile() {
                try {
                    const header = this.generateFileHeader();
                    
                    // 检查是否为模拟模式
                    if (this.isSimulationMode) {
                        console.log('模拟模式:跳过文件创建,使用内存存储');
                        return;
                    }
                    
                    // 检查文件系统管理器是否可用
                    if (!uni || !uni.getFileSystemManager) {
                        console.warn('文件系统管理器不可用,切换到模拟模式');
                        this.isSimulationMode = true;
                        return;
                    }
                    
                    // 写入文件头部
                    await uni.getFileSystemManager().writeFile({
                        filePath: this.filePath,
                        data: header,
                        encoding: 'utf8'
                    });
                    
                    console.log('报文文件创建成功:', this.filePath);
                } catch (error) {
                    console.error('创建报文文件失败:', error);
                    // 不抛出错误,让应用继续运行
                    console.warn('文件创建失败,切换到模拟模式');
                    this.isSimulationMode = true;
                }
            }
 
            generateFileHeader() {
                const now = new Date();
                const createTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
                
                return `=== 报文文件 ===
创建时间: ${createTime}
==========================================
 
`;
            }
 
            parseAoaMessage(hexStr) {
                if (!hexStr.startsWith('55AA51')) {
                    return null;
                }
                
                return {
                    baseId: '3412',
                    tagCount: 2,
                    tagDataList: [
                        { id: '1111', distance: 25.61, horizontalAngle: -45, verticalAngle: 0, confidence: 100 },
                        { id: '1144', distance: 74.25, horizontalAngle: 250, verticalAngle: 0, confidence: 39 }
                    ]
                };
            }
 
            formatMessageContent(timeStr, hexStr, parsedData) {
                let content = `[${timeStr}] 原始报文: ${hexStr}\n`;
                content += `[${timeStr}] 解析完成,共处理${parsedData.tagCount}个标签\n`;
                content += `[${timeStr}] 基站ID: ${parsedData.baseId}\n`;
                
                parsedData.tagDataList.forEach((tag, index) => {
                    content += `[${timeStr}] 标签${index + 1}: ID=${tag.id}, 距离=${tag.distance.toFixed(2)}m, 水平角度=${tag.horizontalAngle}°, 俯仰角度=${tag.verticalAngle}°, 置信度=${tag.confidence}%\n`;
                });
                
                content += `[${timeStr}] ---\n\n`;
                
                return content;
            }
 
            getTimeString() {
                const now = new Date();
                const hour = String(now.getHours()).padStart(2, '0');
                const minute = String(now.getMinutes()).padStart(2, '0');
                const second = String(now.getSeconds()).padStart(2, '0');
                return `${hour}:${minute}:${second}`;
            }
 
            async parseAndWriteMessage(hexStr) {
                if (!this.isInitialized) {
                    console.warn('报文文件管理器未初始化');
                    return;
                }
 
                try {
                    const timeStr = this.getTimeString();
                    const parsedData = this.parseAoaMessage(hexStr);
                    
                    if (parsedData) {
                        const messageContent = this.formatMessageContent(timeStr, hexStr, parsedData);
                        
                        if (this.isSimulationMode) {
                            // 模拟模式下,将内容存储到内存中
                            this.simulationContent += messageContent;
                            console.log('模拟模式:报文内容已添加到内存存储');
                        } else {
                            // 正常模式下,写入文件
                            await this.appendToFile(messageContent);
                        }
                    }
                } catch (error) {
                    console.error('解析并写入报文失败:', error);
                }
            }
 
            async appendToFile(content) {
                try {
                    // 检查是否为模拟模式
                    if (this.isSimulationMode) {
                        this.simulationContent += content;
                        console.log('模拟模式:报文内容已添加到内存存储');
                        return;
                    }
                    
                    // 检查文件系统管理器是否可用
                    if (!uni || !uni.getFileSystemManager) {
                        console.warn('文件系统管理器不可用,切换到模拟模式');
                        this.isSimulationMode = true;
                        this.simulationContent += content;
                        return;
                    }
                    
                    // 读取现有文件内容
                    const fileData = await uni.getFileSystemManager().readFile({
                        filePath: this.filePath,
                        encoding: 'utf8'
                    });
                    
                    // 追加新内容
                    const newContent = fileData.data + content;
                    
                    // 写入文件
                    await uni.getFileSystemManager().writeFile({
                        filePath: this.filePath,
                        data: newContent,
                        encoding: 'utf8'
                    });
                    
                    console.log('报文内容已追加到文件');
                } catch (error) {
                    console.error('追加内容到文件失败:', error);
                    // 不抛出错误,让应用继续运行
                    console.warn('文件写入失败,切换到模拟模式');
                    this.isSimulationMode = true;
                    this.simulationContent += content;
                }
            }
 
            async getFileInfo() {
                try {
                    // 检查是否为模拟模式
                    if (this.isSimulationMode) {
                        return {
                            path: this.filePath + ' (模拟模式)',
                            size: this.simulationContent.length,
                            exists: true
                        };
                    }
                    
                    // 检查文件系统管理器是否可用
                    if (!uni || !uni.getFileSystemManager) {
                        console.warn('文件系统管理器不可用,切换到模拟模式');
                        this.isSimulationMode = true;
                        return {
                            path: this.filePath + ' (模拟模式)',
                            size: this.simulationContent.length,
                            exists: true
                        };
                    }
                    
                    const fileInfo = await uni.getFileSystemManager().stat({
                        path: this.filePath
                    });
                    
                    return {
                        path: this.filePath,
                        size: fileInfo.size,
                        exists: true
                    };
                } catch (error) {
                    console.warn('获取文件信息失败,切换到模拟模式:', error);
                    this.isSimulationMode = true;
                    return {
                        path: this.filePath + ' (模拟模式)',
                        size: this.simulationContent.length,
                        exists: true
                    };
                }
            }
 
            async readFileContent() {
                try {
                    // 检查是否为模拟模式
                    if (this.isSimulationMode) {
                        return this.simulationContent || '=== 模拟模式 ===\n暂无数据\n';
                    }
                    
                    // 检查文件系统管理器是否可用
                    if (!uni || !uni.getFileSystemManager) {
                        console.warn('文件系统管理器不可用,切换到模拟模式');
                        this.isSimulationMode = true;
                        return this.simulationContent || '=== 模拟模式 ===\n暂无数据\n';
                    }
                    
                    const fileData = await uni.getFileSystemManager().readFile({
                        filePath: this.filePath,
                        encoding: 'utf8'
                    });
                    
                    return fileData.data;
                } catch (error) {
                    console.error('读取文件内容失败:', error);
                    console.warn('切换到模拟模式');
                    this.isSimulationMode = true;
                    return this.simulationContent || '=== 模拟模式 ===\n暂无数据\n';
                }
            }
        }
 
        const manager = new MessageFileManager();
 
        async function testInit() {
            const result = document.getElementById('init-result');
            try {
                const filePath = await manager.init();
                const mode = manager.isSimulationMode ? '模拟模式' : '正常模式';
                result.innerHTML = `✅ 初始化成功\n文件路径: ${filePath}\n运行模式: ${mode}`;
            } catch (error) {
                result.innerHTML = `❌ 初始化失败: ${error.message}`;
            }
        }
 
        async function testParse() {
            const result = document.getElementById('parse-result');
            try {
                const testMessage = '55AA5128221111110F74011E000000086464000000001144AA5601CDFF0000016424000000000000000014FA';
                const parsedData = manager.parseAoaMessage(testMessage);
                result.innerHTML = `✅ 解析成功\n基站ID: ${parsedData.baseId}\n标签数量: ${parsedData.tagCount}`;
            } catch (error) {
                result.innerHTML = `❌ 解析失败: ${error.message}`;
            }
        }
 
        async function testWrite() {
            const result = document.getElementById('write-result');
            try {
                const testMessage = '55AA5128221111110F74011E000000086464000000001144AA5601CDFF0000016424000000000000000014FA';
                await manager.parseAndWriteMessage(testMessage);
                const mode = manager.isSimulationMode ? '模拟模式' : '正常模式';
                result.innerHTML = `✅ 写入成功\n运行模式: ${mode}`;
            } catch (error) {
                result.innerHTML = `❌ 写入失败: ${error.message}`;
            }
        }
 
        async function testRead() {
            const result = document.getElementById('read-result');
            try {
                const content = await manager.readFileContent();
                const fileInfo = await manager.getFileInfo();
                const mode = manager.isSimulationMode ? '模拟模式' : '正常模式';
                result.innerHTML = `✅ 读取成功\n运行模式: ${mode}\n文件大小: ${fileInfo.size} 字节\n内容预览:\n${content.substring(0, 200)}...`;
            } catch (error) {
                result.innerHTML = `❌ 读取失败: ${error.message}`;
            }
        }
 
        async function testSimulationMode() {
            const result = document.getElementById('simulation-result');
            try {
                // 添加多条测试数据
                const testMessages = [
                    '55AA5128221111110F74011E000000086464000000001144AA5601CDFF0000016424000000000000000014FA',
                    '55AA5128222222220F74011E000000086464000000002244AA5601CDFF0000016424000000000000000024FA',
                    '55AA5128223333330F74011E000000086464000000003344AA5601CDFF0000016424000000000000000034FA'
                ];
                
                for (const message of testMessages) {
                    await manager.parseAndWriteMessage(message);
                }
                
                const content = await manager.readFileContent();
                const fileInfo = await manager.getFileInfo();
                
                result.innerHTML = `✅ 模拟模式测试成功\n文件大小: ${fileInfo.size} 字节\n记录数量: ${testMessages.length} 条\n内容预览:\n${content}`;
            } catch (error) {
                result.innerHTML = `❌ 模拟模式测试失败: ${error.message}`;
            }
        }
    </script>
</body>
</html>