fei.wang
7 天以前 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
<template>
  <view class="container">
    <view class="test-section">
      <text class="section-title">文件保存测试</text>
      <u-button @click="testSaveFile" type="primary" size="large" class="test-button">
        测试保存文件
      </u-button>
      <u-button @click="testParseMessage" type="success" size="large" class="test-button">
        测试解析报文
      </u-button>
      <u-button @click="showFileStatus" type="info" size="large" class="test-button">
        显示文件状态
      </u-button>
    </view>
    
    <view class="result-section">
      <text class="section-title">测试结果</text>
      <text class="result-text">{{ testResult }}</text>
    </view>
  </view>
</template>
 
<script>
// 导入必要的 Android 类
const android = plus.android;
const Intent = android.importClass('android.content.Intent');
const Settings = android.importClass('android.provider.Settings');
const Uri = android.importClass('android.net.Uri');
const Build = android.importClass('android.os.Build');
const Environment = android.importClass('android.os.Environment');
const MediaStore = android.importClass('android.provider.MediaStore');
const ContentValues = android.importClass('android.content.ContentValues');
const ContentResolver = android.importClass('android.content.ContentResolver');
 
export default {
  data() {
    return {
      testResult: '',
      messageContent: '',
      fileName: 'vehicle_message_log.txt'
    }
  },
  methods: {
    async testSaveFile() {
      try {
        this.testResult = '开始测试文件保存...\n';
        
        const testContent = `[${new Date().toLocaleString()}] 测试报文数据
{
  "type": "55AA51_RAW",
  "hexData": "55AA5128221111110F74011E000000086464000000001144AA5601CDFF0000016424000000000000000014FA",
  "timestamp": "${new Date().toISOString()}"
}
{
  "type": "55AA51_PARSED",
  "baseId": "3412",
  "tagId": "1111",
  "distance": 25.61,
  "hAngle": -45.2,
  "vAngle": 0,
  "signalStrength": 100,
  "angleConfidence": 100,
  "batteryLevel": 100,
  "deviceStatus": 0,
  "pressure": 0,
  "time": "${new Date().toLocaleString()}"
}
`;
        
        // 使用MediaStore API保存文件
        let result = await this.tryWriteWithMediaStore(this.fileName, testContent);
        if (!result) {
          result = await this.tryWriteWithLegacyMethod(this.fileName, testContent);
        }
        
        if (result) {
          this.testResult += `文件保存成功: ${result}\n`;
          uni.showToast({
            title: '测试文件保存成功',
            icon: 'success',
            duration: 3000
          });
        } else {
          this.testResult += '文件保存失败\n';
          uni.showToast({
            title: '测试文件保存失败',
            icon: 'none',
            duration: 3000
          });
        }
      } catch (error) {
        this.testResult += `保存失败: ${error.message}\n`;
        console.error('测试保存失败:', error);
      }
    },
    
    testParseMessage() {
      try {
        this.testResult = '开始测试报文解析...\n';
        
        // 模拟55AA51报文
        const testHex = '55AA5128221111110F74011E000000086464000000001144AA5601CDFF0000016424000000000000000014FA';
        
        // 解析报文
        this.parseAoaMessage(testHex);
        
        this.testResult += '报文解析测试完成\n';
        uni.showToast({
          title: '报文解析测试完成',
          icon: 'success',
          duration: 2000
        });
      } catch (error) {
        this.testResult += `解析失败: ${error.message}\n`;
        console.error('测试解析失败:', error);
      }
    },
    
    showFileStatus() {
      const status = {
        fileName: this.fileName,
        contentLength: this.messageContent.length,
        androidVersion: Build.VERSION.SDK_INT,
        storageState: Environment.getExternalStorageState()
      };
      
      this.testResult = `文件状态信息:
文件名: ${status.fileName}
内容长度: ${status.contentLength} 字符
Android版本: ${status.androidVersion}
存储状态: ${status.storageState}
`;
      
      uni.showModal({
        title: '文件状态',
        content: this.testResult,
        showCancel: false,
        confirmText: '确定'
      });
    },
    
    // 使用 MediaStore API 保存文件 (Android 10+推荐)
    async tryWriteWithMediaStore(fileName, content) {
      return new Promise((resolve) => {
        try {
          // 获取ContentResolver
          const mainActivity = plus.android.runtimeMainActivity();
          const resolver = mainActivity.getContentResolver();
          
          // 设置文件信息
          const contentValues = new ContentValues();
          contentValues.put(MediaStore.Downloads.DISPLAY_NAME, fileName);
          contentValues.put(MediaStore.Downloads.MIME_TYPE, "text/plain");
          
          // 对于Android 10+需要指定RELATIVE_PATH
          if (Build.VERSION.SDK_INT >= 29) {
            contentValues.put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
          }
          
          // 创建文件URI
          const collection = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
          const fileUri = resolver.insert(collection, contentValues);
          
          if (!fileUri) {
            console.error("无法创建文件URI");
            resolve(false);
            return;
          }
          
          // 写入文件内容
          const outputStream = resolver.openOutputStream(fileUri);
          outputStream.write(plus.android.invoke(content, "getBytes", "UTF-8"));
          outputStream.close();
          
          console.log("通过MediaStore写入成功:", fileUri.toString());
          resolve(fileUri.toString());
        } catch (e) {
          console.warn("MediaStore写入失败:", e);
          resolve(false);
        }
      });
    },
    
    // 使用传统文件系统方法保存文件 (兼容旧版Android)
    async tryWriteWithLegacyMethod(fileName, content) {
      return new Promise((resolve) => {
        try {
          // 获取下载目录路径
          const downloadsDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOWNLOADS
          ).toString();
          
          const filePath = `${downloadsDir}/${fileName}`;
          
          // 使用Java文件API写入
          const File = plus.android.importClass('java.io.File');
          const FileOutputStream = plus.android.importClass('java.io.FileOutputStream');
          
          const file = new File(filePath);
          const fos = new FileOutputStream(file);
          fos.write(plus.android.invoke(content, "getBytes", "UTF-8"));
          fos.close();
          
          console.log("传统方法写入成功:", filePath);
          resolve(filePath);
        } catch (e) {
          console.warn("传统方法写入失败:", e);
          resolve(false);
        }
      });
    },
    
    // 模拟报文解析方法
    parseAoaMessage(hexStr) {
      console.log('开始解析55AA51报文:', hexStr);
      
      // 添加原始报文到缓存
      this.addMessageToCache({
        type: '55AA51_RAW',
        hexData: hexStr,
        timestamp: new Date().toISOString()
      });
      
      // 模拟解析结果
      const parsedData = {
        type: '55AA51_PARSED',
        baseId: '3412',
        tagId: '1111',
        distance: 25.61,
        hAngle: -45.2,
        vAngle: 0,
        signalStrength: 100,
        angleConfidence: 100,
        batteryLevel: 100,
        deviceStatus: 0,
        pressure: 0,
        time: new Date().toLocaleString()
      };
      
      // 添加解析后的数据到缓存
      this.addMessageToCache(parsedData);
      
      console.log('报文解析完成');
    },
    
    // 添加报文内容到缓存
    addMessageToCache(messageData) {
      try {
        const timestamp = new Date().toLocaleString();
        const messageLine = `[${timestamp}] ${JSON.stringify(messageData)}\n`;
        
        // 添加到缓存
        this.messageContent += messageLine;
        
        console.log('报文内容已添加到缓存:', messageData);
      } catch (error) {
        console.error('添加报文内容到缓存失败:', error);
      }
    }
  }
}
</script>
 
<style>
.container {
  padding: 40rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}
 
.test-section {
  background: #fff;
  padding: 40rpx;
  border-radius: 20rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 4rpx 15rpx rgba(0,0,0,0.1);
}
 
.section-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
  display: block;
}
 
.test-button {
  margin-bottom: 20rpx;
  width: 100%;
}
 
.result-section {
  background: #fff;
  padding: 40rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 15rpx rgba(0,0,0,0.1);
}
 
.result-text {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
  white-space: pre-wrap;
}
</style>