altosdroid: Add new "TelemetryReader" class to handle Telemetry
[fw/altos] / altosdroid / src / org / altusmetrum / AltosDroid / TelemetryReader.java
1 package org.altusmetrum.AltosDroid;\r
2 \r
3 import java.text.*;\r
4 import java.io.*;\r
5 import java.util.concurrent.*;\r
6 import android.util.Log;\r
7 import android.os.Handler;\r
8 \r
9 import org.altusmetrum.AltosLib.*;\r
10 \r
11 \r
12 public class TelemetryReader extends Thread {\r
13 \r
14         private static final String TAG = "TelemetryReader";\r
15 \r
16         int         crc_errors;\r
17 \r
18         Handler     handler;\r
19 \r
20         AltosLink   link;\r
21         AltosRecord previous;\r
22 \r
23         LinkedBlockingQueue<AltosLine> telem;\r
24 \r
25         public AltosRecord read() throws ParseException, AltosCRCException, InterruptedException, IOException {\r
26                 AltosLine l = telem.take();\r
27                 if (l.line == null)\r
28                         throw new IOException("IO error");\r
29                 AltosRecord     next = AltosTelemetry.parse(l.line, previous);\r
30                 previous = next;\r
31                 return next;\r
32         }\r
33 \r
34         public void close() {\r
35                 previous = null;\r
36                 link.remove_monitor(telem);\r
37                 link = null;\r
38                 telem.clear();\r
39                 telem = null;\r
40         }\r
41 \r
42         public void run() {\r
43                 AltosState  state = null;\r
44 \r
45                 try {\r
46                         for (;;) {\r
47                                 try {\r
48                                         AltosRecord record = read();\r
49                                         if (record == null)\r
50                                                 break;\r
51                                         state = new AltosState(record, state);\r
52 \r
53                                         handler.obtainMessage(TelemetryService.MSG_TELEMETRY, state).sendToTarget();\r
54                                 } catch (ParseException pp) {\r
55                                         Log.e(TAG, String.format("Parse error: %d \"%s\"", pp.getErrorOffset(), pp.getMessage()));\r
56                                 } catch (AltosCRCException ce) {\r
57                                         ++crc_errors;\r
58                                 }\r
59                         }\r
60                 } catch (InterruptedException ee) {\r
61                 } catch (IOException ie) {\r
62                 } finally {\r
63                         close();\r
64                 }\r
65         }\r
66 \r
67         public TelemetryReader (AltosLink in_link, Handler in_handler) {\r
68                 link    = in_link;\r
69                 handler = in_handler;\r
70 \r
71                 previous = null;\r
72                 telem = new LinkedBlockingQueue<AltosLine>();\r
73                 link.add_monitor(telem);\r
74         }\r
75 }\r