Details | Last modification | View Log | RSS feed
Rev | Author | Line No. | Line |
---|---|---|---|
1539 | - | 1 | package dongfang.mkt.serial; |
2 | |||
3 | import java.io.IOException; |
||
4 | import java.io.InputStream; |
||
5 | import java.io.OutputStream; |
||
6 | |||
7 | import dongfang.mkt.frames.RequestFrame; |
||
8 | import dongfang.mkt.frames.ResponseFrame; |
||
9 | import dongfang.mkt.io.MKCommPort; |
||
10 | |||
11 | /** |
||
12 | * Thread safe! |
||
13 | * |
||
14 | * @author dongfang |
||
15 | */ |
||
16 | public class FrameQueue { |
||
17 | private final MKInputStream input; |
||
18 | private final MKOutputStream output; |
||
19 | // private List responseQueue; |
||
20 | private ResponseFrame lastResponseFrame; |
||
21 | private boolean doQueue = true; |
||
22 | |||
23 | class Receiver extends Thread { |
||
24 | public void run() { |
||
25 | while (doQueue) { |
||
26 | try { |
||
27 | ResponseFrame f = input.getNextFrame(); |
||
28 | synchronized (FrameQueue.this.input) { |
||
29 | lastResponseFrame = f; |
||
30 | FrameQueue.this.input.notifyAll(); |
||
31 | } |
||
32 | } catch (IOException ex) { |
||
33 | System.err.println(ex); |
||
34 | } |
||
35 | } |
||
36 | System.out.println("Receiver terminated."); |
||
37 | } |
||
38 | } |
||
39 | |||
40 | public FrameQueue(MKCommPort port) throws IOException { |
||
41 | super(); |
||
42 | this.input = new MKInputStream (port.getInputStream()); |
||
43 | this.output = new MKOutputStream(port.getOutputStream()); |
||
44 | new Receiver().start(); |
||
45 | } |
||
46 | |||
47 | public FrameQueue(InputStream in, OutputStream out) throws IOException { |
||
48 | super(); |
||
49 | this.input = new MKInputStream (in); |
||
50 | this.output = new MKOutputStream(out); |
||
51 | new Receiver().start(); |
||
52 | } |
||
53 | |||
54 | public void sendRequest(RequestFrame f) throws IOException { |
||
55 | synchronized (this.output) { |
||
56 | output.write(f); |
||
57 | } |
||
58 | } |
||
59 | |||
60 | public ResponseFrame getResponseFor(RequestFrame f, int maxwait) throws IOException { |
||
61 | ResponseFrame response; |
||
62 | long timeout = System.currentTimeMillis() + maxwait; |
||
63 | synchronized (input) { |
||
64 | while ((response = responseTo(f)) == null && System.currentTimeMillis() < timeout) { |
||
65 | try { |
||
66 | input.wait(100); |
||
67 | } catch (InterruptedException ex) { |
||
68 | } |
||
69 | } |
||
70 | } |
||
71 | return response; |
||
72 | } |
||
73 | |||
74 | public void kill() { |
||
75 | doQueue = false; |
||
76 | } |
||
77 | |||
78 | private ResponseFrame responseTo(RequestFrame f) { |
||
79 | synchronized (this.input) { |
||
80 | if (lastResponseFrame != null && lastResponseFrame.isResponseTo(f)) { |
||
81 | ResponseFrame result = lastResponseFrame; |
||
82 | lastResponseFrame = null; |
||
83 | return result; |
||
84 | } |
||
85 | return null; |
||
86 | } |
||
87 | } |
||
88 | } |